Reputation: 28744
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
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
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
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