如何在Python中将print语句变成单行输出?

4
如何使这段代码以一行的形式打印出来?
 print("If a hippo ways 2000 pounds, gives birth to a 100 pound calf and
          then eats a 50 pound meal how much does she weigh?")

我这样做是为了使它更易读,我知道我可以使用三引号来打印它的确切方式,并且我可以使用逗号将语句分成两行,但那会生成两个单独的字符串(我想)。有没有办法将该语句保留为一个字符串并将其打印为一行?
2个回答

13

相邻的字符串字面量会被隐式地连接起来:

print("If a hippo ways 2000 pounds, gives birth to a 100 pound calf and "
       "then eats a 50 pound meal how much does she weigh?")

1
print("If a hippo ways 2000 pounds, gives birth to a 100 pound calf and "\
      +"then eats a 50 pound meal how much does she weigh?")

2
在括号/花括号/方括号内,不需要显式的行继续符。事实上,一些人(包括PEP 8的作者)认为这总是优于“\”。 - user395760
带反斜杠的解决方案可以工作,但很丑。 - Matthias
好的,我不知道相邻字符串会自动拼接,谢谢! - GHL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接