py_9
py_9

Reputation: 65

SyntaxError: unexpected character after line continuation character

I am testing a code with doctest and I want to comment in front of the tests like this:

Tests:
>>> part([('Eva', 'Sao Paulo', 21098, '04-12', 1182),\    #False, 1, 0
    ('Ana', 'Toquio', 21098, '06-12', 1182),\
    ('Ana', 'Sao Paulo', 21098, '04-12', 1096)])
    [2, 1]

The problem is that when I run the code in the shell it gives me a synthax error:

File "/home/user/Desktop/file.py", line 44, in __main__.part
Failed example:
    part([('Eva', 'Sao Paulo', 21098, '04-12', 1182),\     #False, 1, 0
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python2.7/doctest.py", line 1315, in __run
        compileflags, 1) in test.globs
      File "<doctest __main__.part[2]>", line 1
        part([('Eva', 'Sao Paulo', 21098, '04-12', 1182),\     #False, 1, 0
                                                                                   ^
    SyntaxError: unexpected character after line continuation character

Upvotes: 1

Views: 11842

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

You can't put anything after the line continuation character \. You have comments after the backslash:

... \     #False, 1, 0

Remove the comment, the newline has to directly follow the \:

part([('Eva', 'Sao Paulo', 21098, '04-12', 1182),\
    ('Ana', 'Toquio', 21098, '06-12', 1182),\
    ('Ana', 'Sao Paulo', 21098, '04-12', 1096)])\
    [2, 1]

Note the extra \ after the part(..) call to ensure the [2, 1] slice is part of it! See the Explicit line joining section of the reference documentation:

A line ending in a backslash cannot carry a comment. [...] A backslash is illegal elsewhere on a line outside a string literal.

However, you don't need to use a line continuation character at all within parentheses, the logical line is automatically extended until all parentheses and brackets are closed:

part([('Eva', 'Sao Paulo', 21098, '04-12', 1182),    # False, 1, 0
      ('Ana', 'Toquio', 21098, '06-12', 1182),
      ('Ana', 'Sao Paulo', 21098, '04-12', 1096)])[2, 1]

You can include comments when relying on the parentheses to extend the logical line.

From the Implicit line joining section:

Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. [...] Implicitly continued lines can carry comments.

Upvotes: 7

Related Questions