SyntaxError: unexpected character after line continuation character

前端 未结 1 457
天涯浪人
天涯浪人 2021-01-26 19:16

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         


        
1条回答
  •  借酒劲吻你
    2021-01-26 19:48

    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.

    0 讨论(0)
提交回复
热议问题