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

后端 未结 4 1800
挽巷
挽巷 2021-01-05 14:37

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


        
4条回答
  •  难免孤独
    2021-01-05 15:05

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

提交回复
热议问题