python - 字符串语法不正确,占用超过 1 行 Python

标签 python python-2.7

我正在尝试创建一个程序来分配任何人键入的内容以响应特定提示,它占用了两行以上,而且我担心它无法识别字符串,因为它在不同的行上。它不断弹出“语法不正确”错误,并一直指向下面的行。有什么办法可以解决这个问题吗?

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/

相关文章:

python - BeautifulSoup - 处理 variable.find().string 返回空的情况

python-2.7 - 图形工具 -> Networkx

python - + :'Decimal' 和 'Decimal' 不支持的操作数类型

python - JenkinsAPI Python - 尝试获取构建信息

python - 配置 Django 日志记录 - SQL 和其他消息

python - 对 python 类同时使用 __setattr__ 和描述符

python - 我的抓取工具产生了太多的项目,而不是将它们全部合并成一小堆

python - Django 查询集缓存与exists() 和values_list()

python - 满足这个标准的语言?

python - 如何在背景 OpenCV 和 Python 上调整和转换蒙版图像的大小