Print a list of space-separated elements in Python 3 -


i have list l of elements, natural numbers. want print them in 1 line single space separator. don't want space after last element of list (or before first).

in python 2, can done following code. implementation of print statement (mysteriously, must confess) avoids print space before newline.

l = [1, 2, 3, 4, 5] x in l:     print x, print 

however, in python 3 seems (supposedly) equivalent code using print function produces space after last number:

l = [1, 2, 3, 4, 5] x in l:     print(x, end=" ") print() 

of course there easy answers question. know can use string concatenation:

l = [1, 2, 3, 4, 5] print(" ".join(str(x) x in l)) 

this quite solution, compared python 2 code find counter-intuitive , slower. also, know can choose whether print space or not myself, like:

l = [1, 2, 3, 4, 5] i, x in enumerate(l):     print(" " if i>0 else "", x, sep="", end="") print() 

but again worse had in python 2.

so, question is, missing in python 3? behavior i'm looking supported print function?

you can apply list separate arguments:

print(*l) 

and let print() take care of converting each element string. can, always, control separator setting sep keyword argument:

>>> l = [1, 2, 3, 4, 5] >>> print(*l) 1 2 3 4 5 >>> print(*l, sep=', ') 1, 2, 3, 4, 5 >>> print(*l, sep=' -> ') 1 -> 2 -> 3 -> 4 -> 5 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -