【问题标题】:Python 2.7.13 multiline printPython 2.7.13 多行打印
【发布时间】:2017-03-10 12:25:59
【问题描述】:

这是一个初学者的问题。我正在写一个文字游戏,但遇到了一些问题。

代码:

def river():
    print "You are traveling through deciduous forest."
    print "There is nothing going on, except a few squirrels and a hedge."
    print "Squirrels are fighting over nuts and a hedge is getting fat eating an apple."
    print "Then you see a wide, deep river. The stream is very strong."
    print "What are you going to do next?"
    print "1. Try to swim the river."
    print "2. Watch the squirrels and hedge."
    print "3. Turn back."

    while True:
        choice = raw_input("> ")

        if choice == "1" or choice == "swim":
            print """You are doing well when in the middle of a river
something begins to bite you near legs. The bitting gets stronger
and you soon realize that piranhas are tearing chunks of your meat
off. Soon there is nothing left of you that the bones. The piranhas
seems satisfied, since they got a free meal."""
            dead()
        if choice == "2" or choice == "watch":
            print "You keep watching animals and are becoming more and more thirsty and hungry."
        if choice == "3" or choice == "turn back" or choice == "turn":
            start_rewind()

start()

我不喜欢这些打印语句。如果我使用多行打印,例如在选项 1 下,缩进看起来不太好。它与 def river() 位于同一行。这是正常的还是坏的风格?如果我缩进选项 I 下的文本,使其与选项 1 在同一行,.. 那么当我在命令提示符中启动脚本时它看起来不太好。我怎么能解决这个问题?

谢谢

【问题讨论】:

  • 为什么不在print 语句中使用\n

标签: python printing indentation multiline


【解决方案1】:

我会这样写:

print ("You are traveling through deciduous forest.\n"
       "There is nothing going on, except a few squirrels and a hedge.\n"
       "Squirrels are fighting over nuts and a hedge is getting fat eating an apple.\n"
       "Then you see a wide, deep river. The stream is very strong.")

上面的括号隐式地延续了字符串。见the Python docs。例如:

print ("foo "
       "bar")

print "foo bar"

将给出相同的输出。注意“foo”后面的空格。

注意print 语句和第一个括号之间有一个空格。在python3中,print是一个函数,那里应该没有空格。

【讨论】:

    【解决方案2】:

    试试这个:

    print("""
    You are traveling through deciduous forest.
    There is nothing going on, except a few squirrels and a hedge.
    Squirrels are fighting over nuts and a hedge is getting fat eating an apple.
    Then you see a wide, deep river. The stream is very strong.
    What are you going to do next?
    1. Try to swim the river.
    2. Watch the squirrels and hedge.
    3. Turn back.
    """)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多