我可以在三引号字符串的开头添加其他引号,但不能在结尾添加其他引号。这是为什么?此代码块:
print(""""
String that starts with quadruple quotes and ends with triple quotes
""")
产生以下输出:
"
String that starts with quadruple quotes and ends with triple quotes
但是此代码块不起作用:
print(""""
String that starts with quadruple quotes and ends with quadruple quotes
"""")
它产生此错误:
File "example.py", line 3
"""")
^
SyntaxError: EOL while scanning string literal
我从来不需要使用四引号字符串,但我很好奇Python为什么不允许我这样做。谁能帮我理解?
您不能在三引号字符串中使用"""
任何值。不是在一开始,也不是在结尾。
这是因为,前三后"""
开盘字符表示这样的字符串的开始,另一个序列"""
是始终将是字符串的结尾。您的第四个"
位于您创建的字符串对象之外,"
没有结束"
符的单个无效字符串。
Python没有其他方法知道这种字符串何时结束。您不能"
在final之前随意将字符串“向内”扩展为其他字符"""
,因为这与有效和合法的*是没有区别的:
>>> """string 1"""" string 2"
'string 1 string 2'
如果必须"
在结束前加上a """
,请对其进行转义。您可以在其前面加上反斜杠来实现:
>>> """This is triple-quoted string that
... ends in a single double quote: \""""
'This is triple-quoted string that\nends in a single double quote: "'
注意,不存在四引号字符串。Python不允许您将"
引号任意组合成更长的序列。仅存在"single quoted"
和"""triple-quoted"""
语法(使用"
或'
)。三引号字符串的规则不同于单引号字符串。前者允许使用换行符,而后者则不允许。
有关更多详细信息,请参见参考文档的字符串和字节文字部分,该文件将语法定义为:
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"' longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
并明确提到:
在三引号文字中,允许(并保留)未转义的换行符和引号,但一行中三个未转义的引号会终止文字。(“引号”是用于打开文字的字符,即
'
或"
。)
(强调粗体)。
*该表达式是合法的,因为它包含两个字符串文字,一个带"""
引号,另一个带"
引号。连续字符串文字会自动连接,就像在C中一样。请参见String文字串联。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句