Python: print all the string from list at the same time

房东的猫 提交于 2021-01-28 11:50:26

问题


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.

Code:

a=['a is apple','b is banana','c is cherry']
for i in a:
    print(i)
print("====================")
print(i)

It prints:

a is apple
b is banana
c is cherry
====================
c is cherry

What I want for the result is:

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry

回答1:


You can use print with * and a separator of a newline:

print(*a, sep='\n')
print("====================")
print(*a, sep='\n')

Output:

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry

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')

Output:

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry

In Python 2 "turn on" the Python-3-style print function with:

from __future__ import print_function



回答2:


You can multiply list by 2 and append separator in middle of the list and then simply print the list using join method.

l = ['a is apple','b is banana','c is cherry']
l = l*2 
#['a is apple', 'b is banana', 'c is cherry', 'a is apple', 'b is banana', 'c is cherry']
l = l.insert(int(len(l)/2), '====================')
#['a is apple', 'b is banana', 'c is cherry', '====================','a is apple', 'b is banana', 'c is cherry']
print('\n'.join(l))

This will output:

a is apple
b is banana
c is cherry
====================
a is apple 
b is banana
c is cherry



回答3:


You can use join() and pass list to it as follows:

a=['a is apple','b is banana','c is cherry']
print("\n".join(a))
print("====================")
print("\n".join(a))

output

a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry



回答4:


Try this one. This will give what you need

x,y,z=a
print(x,y,z)



回答5:


This is the simplest and cleanest way of doing it (universal across Python 2 and 3):

print('\n'.join(a + ["===================="] + a))

This is the Python-3-only version:

print(*(a + ["===================="] + a), sep='\n')


来源:https://stackoverflow.com/questions/47919179/python-print-all-the-string-from-list-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!