使用python中的符号拆分字符串(Splitting the string using a symbol in python)
我有以下字符串:
my_string = '1) ServerName sn = ProtobufUtil.toServerName(request.getServer());\\n2) String msg = "Region server " + sn +\\n3) " reported a fatal error:\\\\n" + errorText;\\n4) LOG.error(msg);'我需要将该字符串转换为按符号\\n分割的列表。 所以,列表将是这样的:
my_list = ['1) ServerName sn = ProtobufUtil.toServerName(request.getServer());', '2) String msg = "Region server " + sn +', '3) " reported a fatal error:\\\\n" + errorText;', '4) LOG.error(msg);' ]我在代码中使用符号\\n作为拆分器:
my_list = my_string.split("\\n")但是,列表中第三个元素的输出并不像我预期的那样。 输出:
my_list = ['1) ServerName sn = ProtobufUtil.toServerName(request.getServer());', '2) String msg = "Region server " + sn +', '3) " reported a fatal error:\\', '" + errorText;', '4) LOG.error(msg);']如何在代码中定义拆分器?
I have the following string:
my_string = '1) ServerName sn = ProtobufUtil.toServerName(request.getServer());\\n2) String msg = "Region server " + sn +\\n3) " reported a fatal error:\\\\n" + errorText;\\n4) LOG.error(msg);'I need to convert that string into a list split by symbol \\n. So, the list will be like this:
my_list = ['1) ServerName sn = ProtobufUtil.toServerName(request.getServer());', '2) String msg = "Region server " + sn +', '3) " reported a fatal error:\\\\n" + errorText;', '4) LOG.error(msg);' ]I used the symbol \\n as the splitter in my code:
my_list = my_string.split("\\n")However, the output for the third element in the list is not as I expected. Output:
my_list = ['1) ServerName sn = ProtobufUtil.toServerName(request.getServer());', '2) String msg = "Region server " + sn +', '3) " reported a fatal error:\\', '" + errorText;', '4) LOG.error(msg);']How should the splitter be defined in the code?
最满意答案
除了正则表达式选项,你别无选择。 你可以使用re.split和负面的re.split来做到这一点。
>>> import re >>> re.split(r'(?<!\\)\\n', my_string) [ '1) ServerName sn = ProtobufUtil.toServerName(request.getServer())', '2) String msg = "Region server " + sn ', '3) " reported a fatal error:\\\\n" + errorText', '4) LOG.error(msg);' ]lookbehind指定只有在\\n前面没有更多反斜杠时才能进行拆分。
You've got no option but the regex option. You can do this with re.split, and a negative lookbehind.
>>> import re >>> re.split(r'(?<!\\)\\n', my_string) [ '1) ServerName sn = ProtobufUtil.toServerName(request.getServer())', '2) String msg = "Region server " + sn ', '3) " reported a fatal error:\\\\n" + errorText', '4) LOG.error(msg);' ]The lookbehind specifies that the split must occur only when \\n isn't preceded by more backslashes.
更多推荐
发布评论