为什么在Python 3中,四重引号会产生语法错误?

bpe*_*pep 3 python string python-3.x

我可以在三引号字符串的开头添加其他引号,但不能添加到结尾.这是为什么?这段代码:

print(""""
String that starts with quadruple quotes and ends with triple quotes
""")
Run Code Online (Sandbox Code Playgroud)

生成此输出:

"
String that starts with quadruple quotes and ends with triple quotes
Run Code Online (Sandbox Code Playgroud)

但是这个代码块不起作用:

print(""""
String that starts with quadruple quotes and ends with quadruple quotes
"""")
Run Code Online (Sandbox Code Playgroud)

它会产生以下错误:

  File "example.py", line 3
    """")
        ^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)

我不需要使用四重引用字符串,但我很好奇为什么Python不会让我这样做.谁能帮我理解?

Mar*_*ers 7

您不能在三引号字符串的值中使用""" 任何位置.不是在开始时,而是在最后.

这是因为,经过前三个"""开放字符表示这样的字符串的开始,另一个序列"""始终将是字符串的结尾.您的第四个"位于您创建的字符串对象之外,而"没有关闭的单个"字符串不是有效的字符串.

Python没有其他方法可以知道这样的字符串何时结束."在决赛之前,你不能随意用字符"向内"扩展字符串""",因为这与有效和合法的*无法区分:

>>> """string 1"""" string 2"
'string 1 string 2'
Run Code Online (Sandbox Code Playgroud)

如果你必须"在结束前包括一个""",请逃避它.您可以在前面加上反斜杠来执行此操作:

>>> """This is triple-quoted string that
... ends in a single double quote: \""""
'This is triple-quoted string that\nends in a single double quote: "'
Run Code Online (Sandbox Code Playgroud)

请注意,不存在四重引用字符串.Python不允许您将"引号任意组合成更长的序列.只有"single quoted""""triple-quoted"""存在语法错误(使用"').三引号字符串的规则与单引号字符串不同; 前者允许换行,而后者不允许换行.

有关更多详细信息,请参阅参考文档的String和Bytes文字部分,该部分将语法定义为:

shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
Run Code Online (Sandbox Code Playgroud)

并明确提到:

在三引号文字中,允许(并保留)未转义的换行符和引号,除了连续三个未转义的引号终止文字.("引用"是用于打开文字的字符,即'或者".)

(大胆强调我的).


*表达式是合法的,因为它包含两个字符串文字,一个带"""引号,下一个带"引号.连续字符串文字会自动连接,就像它们在C中一样.请参阅字符串文字连接.