可以在.format()方法中添加换行符吗?

时间:2014-08-16 19:05:38

标签: python python-3.x

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

John Doe
123 Main Street
AnyCity, AS 09876

我试图通过一个打印声明来确定是否可以这样做,但我无法弄清楚如何使用添加换行符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'

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

2 个答案:

答案 0 :(得分:12)

如果你print它就有效。请阅读this post解释print vs repr

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

输出

John Doe
123 Main Street
AnyCity, AS 09876

如果您只是在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'"

答案 1 :(得分:0)

不确定为什么我在其他任何地方都找不到此答案,但是:

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

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