Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 转义字符串并立即将其拆分_Python_Regex_Split - Fatal编程技术网

Python 转义字符串并立即将其拆分

Python 转义字符串并立即将其拆分,python,regex,split,Python,Regex,Split,我有以下代码: import re key = re.escape('#one #two #some #tests #are #done') print(key) key = key.split() print(key) 以及以下输出: \#one\ \#two\ \#some\ \#tests\ \#are\ \#done ['\\#one\\', '\\#two\\', '\\#some\\', '\\#tests\\', '\\#are\\', '\\#done'] 为什么反斜杠会重

我有以下代码:

import re

key = re.escape('#one #two #some #tests #are #done')
print(key)
key = key.split()
print(key)
以及以下输出:

\#one\ \#two\ \#some\ \#tests\ \#are\ \#done
['\\#one\\', '\\#two\\', '\\#some\\', '\\#tests\\', '\\#are\\', '\\#done']
为什么反斜杠会重复?我只想让它们在我的列表中出现一次,因为我想在正则表达式中使用这个列表

提前谢谢!John

每个字符串只有一个反斜杠,但是当打印字符串的
repr
时,它们会被复制(转义)-就像使用字符串构建正则表达式时需要复制它们一样。所以一切都很好

例如:

>>> len("\\")
1
>>> len("\\n")
2
>>> len("\n")
1
>>> print "\\n"
\n
>>> print "\n"


>>>

反斜杠不重复。要实现这一点,请尝试执行以下操作:

for element in key:
    print element
您将看到以下输出:

\#one\
\#two\
\#some\
\#tests\
\#are\
\#done
当您打印整个列表时,python使用了表示法,其中字符串不是按原样打印的,而是按python表达式打印的(请注意引号“”,它们不在字符串中)


要对包含反斜杠的字符串进行实际编码,需要复制该反斜杠。就是这样。

字符是转义字符,即改变后续字符含义的字符。例如,“n”字符只是一个“n”。但是如果您像“\n”一样转义它,它将成为“换行符”。因此,如果需要使用\文字,则需要使用。。。本身:\\

当您将列表转换为字符串(例如打印它)时,它会对列表中包含的每个对象调用
repr
。这就是为什么在第二行输出中会有引号和额外的反斜杠。试试这个:

s = "\\a string with an escaped backslash"
print s       # prints: \a string with an escaped backslash
print repr(s) # prints: '\\a string with an escaped backslash'

repr
调用在字符串周围加引号,并显示反斜杠转义。

哦,我明白了,谢谢!另一个简短的问题:有没有办法告诉
re.escape
不要跳出空白?@JohnSmith:No,
re.escape()
。这有点过分了,但不应该痛。事实上,如果在编译正则表达式时使用
re.VERBOSE
,则转义空白是必要的。在您的情况下,它确实会造成伤害,但您可以通过切换操作来轻松解决这一问题:首先拆分,然后转义:
key=[re.escape(item)for item In key.split()]