【问题标题】:What is wrong with this python code [closed]这个python代码有什么问题[关闭]
【发布时间】: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


    【解决方案1】:

    首先,要解决您的问题,请注意换行符 \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 了解如何在缩进块中使其更整洁)。

    【讨论】:

      【解决方案2】:

      将换行符放在双引号内。

      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
      

      【讨论】:

        猜你喜欢
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-31
        • 2014-08-12
        • 2011-03-30
        • 1970-01-01
        相关资源
        最近更新 更多