SyntaxError: unexpected character after line continuation character

戏子无情 提交于 2019-12-02 09:27:08

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/36657830/syntaxerror-unexpected-character-after-line-continuation-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!