1

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 ?

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
zjffdu
  • 25,496
  • 45
  • 109
  • 159

3 Answers3

6

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
georg
  • 211,518
  • 52
  • 313
  • 390
  • what happens in this case `str = ''''''''jeff'''`, it has only 3 trailing quotes and still an error – avasal Feb 15 '12 at 08:41
1

Only use 3 quotes.

The second string is interpreted as: "jeff

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

Jan B. Kjeldsen
  • 17,817
  • 5
  • 32
  • 50
0

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

Community
  • 1
  • 1