Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 398
MSK Avatar asked Nov 12 '13 22:11

MSK


People also ask

How do you print each item of a list on a separate line Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print multiple items on one line Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do I print multiple variables on the same line?

You can use the cat() function to easily print multiple variables on the same line in R. This function uses the following basic syntax: cat(variable1, variable2, variable3, ...)

How do you print a string on another line in Python?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.


1 Answers

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
like image 197
Martijn Pieters Avatar answered Sep 21 '22 00:09

Martijn Pieters