Python以一种特殊的方式处理文本字符串中的\
因此,您可以键入'\n'来表示换行符或'\t'来表示制表符
由于'\&'对Python来说并不意味着什么特殊的东西,因此Python词法分析器会隐式地为您添加额外的\。
实际上,最好使用\\&或r'\&',而不是'\&'
这里的r意味着原始字符串并且意味着\不被特殊处理,除非它正好在字符串开头的引号字符之前。
在交互式控制台中,Python使用repr来显示结果,所以这就是为什么您会看到双'\'。如果您print您的字符串或使用len(string)您将看到它实际上只有两个字符
一些例子>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".
要澄清彼得在评论中的观点,请参阅this linkUnlike Standard C, all unrecognized
escape sequences are left in the
string unchanged, i.e., the backslash
is left in the string. (This behavior
is useful when debugging: if an escape
sequence is mistyped, the resulting
output is more easily recognized as
broken.) It is also important to note
that the escape sequences marked as
“(Unicode only)” in the table above
fall into the category of unrecognized
escapes for non-Unicode string
literals.