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

后端 未结 4 1709
挽巷
挽巷 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:02
    ports = [60, 89, 200]
    
    for p in ports:
        print (p)
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-05 15:10

    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
    >>>
    
    0 讨论(0)
  • 2021-01-05 15:22

    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
    
    0 讨论(0)
提交回复
热议问题