我正在尝试创建一个程序来分配任何人键入的内容以响应特定提示,它占用了两行以上,而且我担心它无法识别字符串,因为它在不同的行上。它不断弹出“语法不正确”错误,并一直指向下面的行。有什么办法可以解决这个问题吗?
given = raw_input("Is " + str(ans) + " your number?
Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate that I guessed correctly")
最佳答案
您需要使用 multi-line strings , 或圆括号,以在 Python 源代码中包装字符串。由于您的字符串已经在括号内,我会使用这个事实。如果字符串在括号内彼此相邻,解释器将自动将它们连接在一起,因此您可以像这样重写代码:
given = raw_input("Is " + str(ans) + " your number?"
"Enter 'h' to indicate the guess is too high. "
"Enter 'l'to indicate the guess is too low. "
"Enter 'b' to indicate that I guessed correctly")
这就像在每个字符串之间有一个 +
一样。你也可以自己写加号,但这不是必须的。
正如我在上面提到的,您也可以使用三引号字符串('''
或 """
)来实现。但这(在我看来) 基本上让你的代码看起来很糟糕,因为它强加了缩进和换行——我更喜欢坚持使用括号。
关于python - 字符串语法不正确,占用超过 1 行 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17244651/