从技术上讲,任何奇数个反斜杠,如文档中所述。
>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
>>> r'\\'
'\\\\'
>>> r'\\\'
File "<stdin>", line 1
r'\\\'
^
SyntaxError: EOL while scanning string literal
解析器似乎只能将原始字符串中的反斜杠视为常规字符(原始字符串不就是这样吗?),但我可能忽略了一些明显的东西。
原因在这一节中用粗体标出的部分解释了:
String quotes can be escaped with a
backslash, but the backslash remains
in the string; for example, r"\"" is a
valid string literal consisting of two
characters: a backslash and a double
quote; r"\" is not a valid string
literal (even a raw string cannot end
in an odd number of backslashes).
Specifically, a raw string cannot end
in a single backslash (since the
backslash would escape the following
quote character). Note also that a
single backslash followed by a newline
is interpreted as those two characters
as part of the string, not as a line
continuation.
原始字符串不是100%原始的,仍然有一些基本的反斜杠处理。
一些建议:
1)如果你需要操作反斜杠的路径,那么标准的python模块os。道路是你的朋友。例如:
os.path.normpath (c: / folder1 /)
2)如果你想构建带有反斜杠的字符串,但在字符串的末尾没有反斜杠,那么原始字符串是你的朋友(在你的字面字符串之前使用'r'前缀)。例如:
r'\one \two \three'
3)如果你需要在变量X中添加一个反斜杠前缀,那么你可以这样做:
X='dummy'
bs=r'\ ' # don't forget the space after backslash or you will get EOL error
X2=bs[0]+X # X2 now contains \dummy
4)如果你需要创建一个带有反斜杠的字符串,那么结合提示2和3:
voice_name='upper'
lilypond_display=r'\DisplayLilyMusic \ ' # don't forget the space at the end
lilypond_statement=lilypond_display[:-1]+voice_name
现在lilypond_statement包含“\DisplayLilyMusic \upper”
巨蟒万岁!:)
n3on