使用python中的符号拆分字符串(Splitting the string using a symbol in python)

系统教程 行业动态 更新时间:2024-06-14 16:57:40
使用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.

更多推荐

本文发布于:2023-04-13 12:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/57dfbfb5e4371b7d910d11f6c90a5f78.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   符号   python   symbol   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!