语法错误,字符串占用超过1行的Python

时间:2013-06-21 21:34:14

标签: 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")

4 个答案:

答案 0 :(得分:6)

您需要使用multi-line strings或括号来包装Python源代码中的字符串。由于你的字符串已经在括号内,我会使用这个事实。如果它们在parens中彼此相邻,解释器将自动将字符串连接在一起,因此您可以像这样重写代码:

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")

这被视为在每个字符串之间存在+。你也可以自己写一些加号,但这不是必需的。

正如我在上面提到的那样,您也可以使用三引号字符串('''""")来实现。但是这个(在我看来)基本上会让你的代码看起来很糟糕,因为它强加了缩进和换行 - 我更喜欢用括号括起来。

答案 1 :(得分:1)

我会使用多行字符串,但您也有以下选项:

>>> print "Hello world, how are you? \
... Foo bar!"
Hello world, how are you? Foo bar!

反斜杠告诉解释器将以下行视为前一行的延续。如果您关心代码块的外观,可以附加+

>>> print "Hello world, how are you? " + \
...       "Foo bar!"
Hello world, how are you? Foo bar!

编辑:正如@moooeeeep所述,这会在语句末尾转义换行符。如果你之后有任何空白,它会搞砸一切。所以,我把这个答案留给仅供参考 - 我不知道它是否有效。

答案 2 :(得分:0)

只需使用多行字符串即可。这样就可以保留字符串文字中的换行符(我假设这是你想要实现的)。

示例:

given = raw_input("""Is %s 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""" % ans)

答案 3 :(得分:-1)

你也可以做三重引用的字符串。 """的开头和结尾可以跨越多行。