Printing each item of a variable on a separate line in Python

不羁的心 提交于 2019-12-19 17:47:02

问题


I am trying to print a list in Python that contains digits and when it prints the items in the list all print on the same line.

print ("{} ".format(ports))

here is my output

[60, 89, 200]

how can I see the result in this form:

60
89
200

I have tried print ("\n".join(ports)) but that does not work.


回答1:


Loop over the list and print each item on a new line:

for port in ports:
    print(port)

or convert your integers to strings before joining:

print('\n'.join(map(str, ports)))

or tell print() to use newlines as separators and pass in the list as separate arguments with the * splat syntax:

print(*ports, sep='\n')

Demo:

>>> ports = [60, 89, 200]
>>> for port in ports:
...     print(port)
... 
60
89
200
>>> print('\n'.join(map(str, ports)))
60
89
200
>>> print(*ports, sep='\n')
60
89
200



回答2:


i have tried print ("\n".join(ports)) but does not work.

You're very close. The only problem is that, unlike print, join doesn't automatically convert things to strings; you have to do that yourself.

For example:

print("\n".join(map(str, ports)))

… or …

print("\n".join(str(port) for port in ports))

If you don't understand either comprehensions or map, both are equivalent* to this:

ports_strs = []
for port in ports:
    ports_strs.append(str(port))
print("\n".join(ports_strs))
del ports_strs

In other words, map(str, ports) will give you the list ['60', '89', '200'].

Of course it would be silly to write that out the long way; if you're going to use an explicit for statement, you might as well just print(port) directly each time through the loop, as in jramirez's answer.


* I'm actually cheating a bit here; both give you an iterator over a sort of "lazy list" that doesn't actually exist with those values. But for now, we can just pretend it's a list. (And in Python 2.x, it was.)




回答3:


ports = [60, 89, 200]

for p in ports:
    print (p)



回答4:


If you are on Python 3.x:

>>> ports = [60, 89, 200]
>>> print(*ports, sep="\n")
60
89
200
>>>

Otherwise, this will work:

>>> ports = [60, 89, 200]
>>> for p in ports:
...     print p
...
60
89
200
>>>


来源:https://stackoverflow.com/questions/19941141/printing-each-item-of-a-variable-on-a-separate-line-in-python

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