Python:同时打印列表中的所有字符串 [英] Python: print all the string from list at the same time
问题描述
例如,我有一个列表 a
.当我在for循环中执行此操作时,可以打印其所有元素.但是,当我在for循环之外执行此操作时,它仅显示最后一个.如何在for循环外将它们全部打印出来?预先感谢.
For example, I have a list a
. When I do it in a for loop, I can print all of its elements. But when I do it outside of the for loop, it only prints the last one. How can I print them all outside the for loop? Thanks in advance.
代码:
a=['a is apple','b is banana','c is cherry']
for i in a:
print(i)
print("====================")
print(i)
它打印:
a is apple
b is banana
c is cherry
====================
c is cherry
我想要的结果是:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
推荐答案
您可以将 print
与 *
和换行符分开使用:
You can use print
with *
and a separator of a newline:
print(*a, sep='\n')
print("====================")
print(*a, sep='\n')
输出:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
print(* a)
等效于 print(a [0],a [1],a [2],...)
.这样可以在中间留有空白.使用 sep ='\ n'
覆盖此默认设置,则会换行.
The print(*a)
is equivalent to print(a[0], a[1], a[2], ...)
.
This would print it with a white space in between.
Overriding this default with sep='\n'
gives you a newline instead.
如果要重用它,请编写自己的小型辅助函数:
If you want to reuse it, write your own, small helper function:
def myprint(a):
print(*a, sep='\n')
myprint(a)
单线替代,但可读性较低:
A one-liner alternative, but arguably less readable:
print(*(a + ["=" * 20] + a), sep='\n')
输出:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
在Python 2中,使用以下命令打开" Python-3样式的打印功能:
In Python 2 "turn on" the Python-3-style print function with:
from __future__ import print_function
这篇关于Python:同时打印列表中的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!