首页 > 解决方案 > Python - 行继续后的无效字符

问题描述

我试图在 Python 中编写一个比较函数:

a = 1
print(
    "1" if a < 1 else \  # Just testing...
    "2" if a == 1 else \ # Testing whether comments work after backslashes
    "3"                  # Last one!
)

添加这些评论后,它给了我一个语法错误:

SyntaxError: unexpected character after line continuation character

标签: python

解决方案


摆脱反斜杠。在这种情况下它们是不必要的,因为您的行在括号内。

print(
    "1" if a < 1 else   # <- a < 1
    "2" if a == 1 else  # <- a == 1
    "3"                 # a > 1
)

我还建议您的评论不是特别有用,因为它们只是在同一行代码中重复一些事情,也许您实际上并不需要它们。


推荐阅读