I can add additional quotes to the beginning of a triple-quoted string, but not to the end. Why is that? This block of code:
print(""""
String that starts with quadruple quotes and ends with triple quotes
""")
Produces this output:
"
String that starts with quadruple quotes and ends with triple quotes
Yet this code block doesn’t work:
print(""""
String that starts with quadruple quotes and ends with quadruple quotes
"""")
It produces this error:
File "example.py", line 3
"""")
^
SyntaxError: EOL while scanning string literal
I don’t ever need to use a quadruple-quote string, but I’m curious why Python won’t let me do it. Can anyone help me understand?
Solution:
You can’t use """ anywhere in the value of a triple-quoted string. Not at the start, and not at the end.
That’s because, after the first three """ opening characters denoting the start of such a string, another sequence of """ is always going to be the end of the string. Your fourth " lies outside of the string object you created, and a single " without a closing " is not a valid string.
Python has no other method of knowing when such a string ends. You can’t arbitrarily extend the string ‘inwards’ with additional " characters before the final """, because that’d be indistinguishable from the valid and legal*:
>>> """string 1"""" string 2"
'string 1 string 2'
If you must include a " before the closing """, escape it. You can do so by preceding it with a backslash:
>>> """This is triple-quoted string that
... ends in a single double quote: \""""
'This is triple-quoted string that\nends in a single double quote: "'
Note that there is no such thing as a quadruple-quote string. Python doesn’t let you combine " quotes into longer sequences arbitrarily. Only "single quoted" and """triple-quoted""" syntax exists (using " or '). The rules for a triple-quoted string differ from a single-quoted string; newlines are allowed in the former, not in the latter.
See the String and Bytes literals section of the reference documentation for more details, which defines the grammar as:
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"' longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
and explicitly mentions:
In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either
'or".)
(bold emphasis mine).
* The expression is legal because it consists of two string literals, one with """ quoting, the next with " quoting. Consecutive string literals are automatically concatenated, just like they would in C. See String literal concatenation.