Python 为什么附加反斜杠'\';使用re.split时是否添加到列表中的子字符串?
因此,我试图解决代码中的一个问题,即使用re.split(regex_pattern,str)后,在拆分列表中的子字符串中添加一个额外的反斜杠。问题是这样的:Python 为什么附加反斜杠'\';使用re.split时是否添加到列表中的子字符串?,python,regex,python-2.7,split,Python,Regex,Python 2.7,Split,因此,我试图解决代码中的一个问题,即使用re.split(regex_pattern,str)后,在拆分列表中的子字符串中添加一个额外的反斜杠。问题是这样的: In [63]: str = r'/dir/hello\/hell/dir2/hello\end' In [64]: regex_pattern = '(hello)' In [65]: a = re.split(regex_pattern, str) In [66]: a Out[66]: ['/dir/', 'hello', '
In [63]: str = r'/dir/hello\/hell/dir2/hello\end'
In [64]: regex_pattern = '(hello)'
In [65]: a = re.split(regex_pattern, str)
In [66]: a
Out[66]: ['/dir/', 'hello', '\\/hell/dir2/', 'hello', '\\end']
如您所见,Out[66]将列表显示为具有两个带“\\”的子字符串,而不是两个带“\”的子字符串。我知道这个问题与编译器如何解释反斜杠有关,但最终无法弄清楚为什么会发生这种情况
我还尝试将str变量设置为原始字符串,并在str变量存在的地方添加额外的“\”(最多四个“\ \”),即
In [63]: str = r'/dir/hello\\/hell/dir2/hello\\end'
这仍然提供相同的输出
我在Ubuntu上使用Python2.7。很抱歉,如果这是重复的,但我找不到一个答案适用于我的问题。这与
re.split
无关<代码>\通常定义转义序列。要使用文字\
,您需要将其加倍:
考虑您的原始字符串:
In [15]: s = r'/dir/hello\/hell/dir2/hello\end'
In [16]: s
Out[16]: '/dir/hello\\/hell/dir2/hello\\end'
In [17]: len(s)
Out[17]: 31
额外的
\
不计入len
。它们只帮助指定\
不定义任何其他转义序列;旁白\\
这也是一个转义序列。这与重新拆分无关<代码>\
通常定义转义序列。要使用文字\
,您需要将其加倍:
考虑您的原始字符串:
In [15]: s = r'/dir/hello\/hell/dir2/hello\end'
In [16]: s
Out[16]: '/dir/hello\\/hell/dir2/hello\\end'
In [17]: len(s)
Out[17]: 31
额外的
\
不计入len
。它们只帮助指定\
不定义任何其他转义序列;旁白\\
这也是一个转义序列。基本上,不用担心。当你将列表打印到屏幕上时,它只是改变了列表的显示方式,但实际的字符串没有任何额外的斜杠。@juanpa.arrivillaga谢谢基本上不用担心。当你将列表打印到屏幕上时,它只是改变了列表的显示方式,但实际的字符串没有任何额外的斜杠。@juanpa.arrivillaga谢谢你。很好地指出了它是如何不影响len()的!非常感谢。很好地指出了它是如何不影响len()的!