zjffdu
zjffdu

Reputation: 28744

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 ?

Upvotes: 1

Views: 790

Answers (3)

Vovk Donets
Vovk Donets

Reputation: 46

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

Upvotes: 0

georg
georg

Reputation: 214949

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

Upvotes: 6

Jan B. Kjeldsen
Jan B. Kjeldsen

Reputation: 18051

Only use 3 quotes.

The second string is interpreted as: "jeff

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

Upvotes: 1

Related Questions