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
Solution 1:
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
Solution 2:
Only use 3 quotes.
The second string is interpreted as: "jeff
The third string is interpreted as: "jeff, followed by a stray quote.
Solution 3:
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
Post a Comment for "Python Triple String Quote Declaration"