【发布时间】:2015-03-15 14:20:10
【问题描述】:
print ("You have two choices:", \n "(1) Get up now", \n "or," \n "(2) Sleep some more and wait till morning")
我真的不明白这段代码有什么问题。当我运行它时,Python 说 “行继续字符后有一个意外字符”,我不明白。
【问题讨论】:
标签: python
print ("You have two choices:", \n "(1) Get up now", \n "or," \n "(2) Sleep some more and wait till morning")
我真的不明白这段代码有什么问题。当我运行它时,Python 说 “行继续字符后有一个意外字符”,我不明白。
【问题讨论】:
标签: python
首先,要解决您的问题,请注意换行符 \n 应在引号内,即字符串文字本身的一部分:
print ("You have two choices:\n(1) Get up now\nor\n(2) Sleep some more and wait till morning")
其次,报错的原因是反斜杠\outside引号用来表示“这个逻辑行继续下一个物理行”,即explicit line joining。这意味着例如:
if some_really_long_predicate and \
this_other_thing:
print("We're here now")
是可以接受的,尽管括号内隐含延续 is preferred:
if (some_really_long_predicate and
this_other_thing):
print("We're here now")
因此当 Python 解析时:
print ("You have two choices:", \n ...
# ^ continuation character
它不希望找到n(有问题的“意外字符”)或任何后续字符。
最后请注意,您可以使用多行字符串来更整齐地写出来:
print("""You have two choices:
(1) Get up now
or
(2) Sleep some more and wait till morning""")
# ^ note triple quotes
(请参阅here 了解如何在缩进块中使其更整洁)。
【讨论】:
将换行符放在双引号内。
In [44]: print("You have two choices:", "\n(1) Get up now", "\nor," "\n(2) Sleep some more and wait till morning")
You have two choices:
(1) Get up now
or,
(2) Sleep some more and wait till morning
【讨论】: