Python 可以向 .format() 方法添加换行符吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25342992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:05:05  来源:igfitidea点击:

Possible to add newline to .format() method?

pythonpython-3.x

提问by Jose Magana

I've been reading a textbook, and I came across an interesting problem, asking me to print an address like so using print statements:

我一直在读一本教科书,我遇到了一个有趣的问题,要求我使用打印语句打印一个地址:

John Doe
123 Main Street
AnyCity, AS 09876

I'm trying to actually figure out if it's possible to do it using oneprint statement, but I can't figure out how to add a newline using the .format() method in Python 3. Here's what I've tried:

我试图真正弄清楚是否可以使用一个打印语句来完成它,但我无法弄清楚如何使用 Python 3 中的 .format() 方法添加换行符。这是我尝试过的:

>>> first = 'John'
>>> last = 'Doe'
>>> street = 'Main Street'
>>> number = 123
>>> city = 'AnyCity'
>>> state = 'AS'
>>> zipcode = '09876'
>>> 
>>> ("{0} {1}\n{2} {3}\n{4}, {5} {6}").format(first, last, number, street, city, state, zipcode)
'John Doe\n123 Main Street\nAnyCity, AS 09876'
>>>
>>> ("{0} {1}'\n'{2} {3}'\n'{4}, {5} {6}").format(first, last, number, street, city, state, zipcode)
"John Doe'\n'123 Main Street'\n'AnyCity, AS 09876"
>>>
>>> ("{0} {1}{7}{2} {3}{8}{4}, {5} {6}").format(first, last, number, street, city, state, zipcode, '\n', '\n')
'John Doe\n123 Main Street\nAnyCity, AS 09876'
>>>
>>> ("{0} {1} \n {2} {3} \n {4}, {5} {6}").format(first, last, number, street, city, state, zipcode)
'John Doe \n 123 Main Street \n AnyCity, AS 09876'

This is probably a super simple question and I'm just missing something really basic. Thanks for the help.

这可能是一个超级简单的问题,我只是缺少一些非常基本的东西。谢谢您的帮助。

采纳答案by Cory Kramer

It works if you printit. Please read this postexplaining printvs repr.

如果你print这样做,它会起作用。请阅读这篇解释printvs 的帖子repr

print ("{0} {1}\n{2} {3}\n{4}, {5} {6}").format(first, last, number, street, city, state, zipcode)

Output

输出

John Doe
123 Main Street
AnyCity, AS 09876

If you just type a variable in IDLE, it actually will use repr, which is why it was represented as a single line.

如果你只是在 IDLE 中输入一个变量,它实际上会使用repr,这就是它被表示为一行的原因。

>>> repr(("{0} {1}\n{2} {3}\n{4}, {5} {6}").format(first, last, number, street, city, state, zipcode))
"'John Doe\n123 Main Street\nAnyCity, AS 09876'"

回答by Howard

Not sure why I couldn't find this answer anywhere else but:

不知道为什么我在其他地方找不到这个答案,但是:

print("{}Walking time is: {:,.3f} hours{}".format("\n", walking_time, "\n"))

worked. Just insert the placeholders and then include the \n in the insert list.

工作。只需插入占位符,然后在插入列表中包含 \n。