可以在.format()方法中添加换行符吗?
我在看一本教科书时,遇到了一个有趣的问题,要求我用打印语句打印出一个地址,格式如下:
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 个回答
5
我不知道为什么在其他地方找不到这个答案,但:
print("{}Walking time is: {:,.3f} hours{}".format("\n", walking_time, "\n"))
这样做有效。只需插入占位符,然后在插入列表中加上 \n。
26
如果你用 print
来输出,它就能正常工作。请查看 这篇文章,它解释了 print
和 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'"