Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python bug - or my stupidity - EOL while scanning string literal

I cannot see a significant difference between the two following lines.

Yet the first parses, and the latter, does not.

In [5]: n=""" \\"Axis of Awesome\\" """

In [6]: n="""\\"Axis of Awesome\\""""
  File "<ipython-input-6-d691e511a27b>", line 1
    n="""\\"Axis of Awesome\\""""
                                ^
SyntaxError: EOL while scanning string literal

Is this a Python bug/feature/oddity, or have I missing something fundamental?

like image 747
Bryan Hunt Avatar asked Jul 04 '12 11:07

Bryan Hunt


People also ask

How do I fix EOL while scanning string literal in Python?

The Python interpreter will return an EOL error if the quotation mark at the end of the string literal is missing. We can easily fix this problem by making sure the end quotation marks are in place. The characters '' and “ can be used to enclose string constants in Python.

What is string literal error?

The JavaScript error "unterminated string literal" occurs when there is an unterminated string literal somewhere. String literals must be enclosed by single ( ' ) or double ( " ) quotes.


1 Answers

The last four quote marks in

"""\\"Axis of Awesome\\""""

are parsed as """, i.e. end of string, followed by ", i.e. start of a new string literal. This new literal is never completed, though. Simple example:

>>> """foo""""bar"
'foobar'
>>> """foo""" "bar"
'foobar'

If you want to avoid this problem, then replace """ with r' or escape the ":

>>> """\\"Axis of Awesome\\\""""
'\\"Axis of Awesome\\"'
>>> r'\"Axis of Awesome\"'
'\\"Axis of Awesome\\"'
like image 197
Fred Foo Avatar answered Oct 20 '22 04:10

Fred Foo