Python bug - or my stupidity - EOL while scanning string literal
Asked Answered
D

2

6

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?

Denti answered 4/7, 2012 at 11:36 Comment(2)
Just use ''' instead of """Unscrupulous
`\` won't escape the quotes, because it's an escaped backslash.Scheming
S
9

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\\"'
Sock answered 4/7, 2012 at 11:39 Comment(0)
C
0

Your last 4 quotation marks are being evaluated as "" & "" instead of what you're expecting it to be evaluated as " & """.

Cyrilcyrill answered 4/7, 2012 at 11:38 Comment(1)
Actually, it's parsed as """, then ".Sock

© 2022 - 2024 — McMap. All rights reserved.