I have a list L
of elements, say natural numbers. I want to print them in one line with a single space as a separator. But I don't want a space after the last element of the list (or before the first).
In Python 2, this can easily be done with the following code. The implementation of the print
statement (mysteriously, I must confess) avoids to print an extra space before the newline.
L = [1, 2, 3, 4, 5] for x in L: print x, print
However, in Python 3 it seems that the (supposedly) equivalent code using the print
function produces a space after the last number:
L = [1, 2, 3, 4, 5] for x in L: print(x, end=" ") print()
Of course there are easy answers to my question. I know I can use string concatenation:
L = [1, 2, 3, 4, 5] print(" ".join(str(x) for x in L))
This is a quite good solution, but compared to the Python 2 code I find it counter-intuitive and definitely slower. Also, I know I can choose whether to print a space or not myself, like:
L = [1, 2, 3, 4, 5] for i, x in enumerate(L): print(" " if i>0 else "", x, sep="", end="") print()
but again this is worse than what I had in Python 2.
So, my question is, am I missing something in Python 3? Is the behavior I'm looking for supported by the print
function?
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.
If you just want to know the best way to print a list in Python, here's the short answer: Pass a list as an input to the print() function in Python. Use the asterisk operator * in front of the list to “unpack” the list into the print function. Use the sep argument to define how to separate two list elements visually.
Use an input() function to accept the list elements from a user in the format of a string separated by space. Next, use a split() function to split an input string by space. The split() method splits a string into a list.
You assign x to a string with a space, then when printing, you simply multiply the string with space by the number of spaces you want before y.
You can apply the list as separate arguments:
print(*L)
and let print()
take care of converting each element to a string. You can, as always, control the separator by setting the 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
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join()
:
joined_string = ' '.join([str(v) for v in L]) print(joined_string) # do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With