Python syntax error: Unexpected character after line continuation character

Python syntax error: Unexpected character after line continuation character

当我 运行 这段代码在 python 3.9 时,我得到了标题中所述的语法错误。我在这里做错了什么?

def grid():
    a = b = c = d = e = f = g = h = i = "_"
    print(a,b,c\nd,e,f\ng,h,i, sep = '|')   

grid()

\ 是一个换行符。 n 是跟在它后面的字符,这是出乎意料的,因为 \ 必须是一行中的最后一个字符。参见:Python language reference – Explicit line joining

如果您打算在 print 输出中插入换行符,换行符本身就是一个字符串 '\n',而不是 Python 语法的一部分。

要么使用字符串连接:

print(a, b, c + '\n' + d, e, f + '\n' + g, h, i, sep = '|')

或者多次调用 print,因为它会自动添加一个换行符:

print(a, b, c, sep = '|')
print(d, e, f, sep = '|')
print(g, h, i, sep = '|')