简体   繁体   中英

Python triple string quote declaration

I use the triple string in the following way:

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

The third one is error, could anyone explain why this is error ?

Three quotes terminate a string, so this

str=""""jeff""""

is parsed as this:

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

The trailing quote is the problem.

BTW, looking at the BNF definition

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

it's obvious that the star * is non-greedy, I don't know though if this is documented somewhere.

In response to the comment, this

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

is interpreted as

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

and this

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

is interpreted as

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

Only use 3 quotes.

The second string is interpreted as: "jeff

The third string is interpreted as: "jeff, followed by a stray quote.

str="""jeff""" --> str 'jeff'

str=""""jeff""" -- > multiline str 'jeff'

str=""""jeff"""" # error --> here parser thinks that you declaring "", "", jeff, "", ""

str=""""jeff """" # error --> same as previous one

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

To avoid it do like this """\\"a \\""""

Also, as tng345 mentioned, you can look in BNF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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