繁体   English   中英

Python三重字符串引用声明

[英]Python triple string quote declaration

我通过以下方式使用三元组字符串:

str="""jeff"""
str=""""jeff"""
str=""""jeff""""   # error
str=""""jeff """"

第三个是错误,有人可以解释为什么这是错误吗?

三个引号终止一个字符串,因此这

str=""""jeff""""

被解析为:

str= """ ("jeff) """ (")

尾随引号是问题所在。

BTW,看看BNF定义

longstring      ::=  "'''" longstringitem* "'''"
                     | '"""' longstringitem* '"""'

很明显,星号*是非贪婪的,我不知道这是否记录在某处。

为了回应评论,

 str = ''''''''jeff'''

被解释为

(''')(''')('')(jeff)(''') <-- error, two quotes

和这个

 str = '''''''''jeff'''

被解释为

 str = (''')(''')(''')(jeff)(''') <-- no error, empty string + jeff

仅使用3个引号。

第二个字符串解释为:“ jeff

第三个字符串解释为:“ jeff,后跟一个引号。

str =“”“ jeff”“”-> str'jeff'

str =“”“” jeff“”“->多行str'jeff'

str =“”“” jeff“”“”“#错误->此处解析器认为您在声明“”,“”,jeff,“”,“”

str =“”“” jeff“”“”#错误->与上一个相同

>>> """"a""""
  File "<stdin>", line 1
    """"a""""
            ^
SyntaxError: EOL while scanning string literal
>>> """"a """"
  File "<stdin>", line 1
    """"a """"
             ^
SyntaxError: EOL while scanning string literal

为了避免这种情况,请像这样“”“ \\” a \\“”“”

另外,如tng345所述,您可以查看BNF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM