Printing a list separated with commas, without a trailing comma
Solution 1
Pass sep=","
as an argument to print()
You are nearly there with the print statement.
There is no need for a loop, print has a sep
parameter as well as end
.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
The print
builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep
. The default value for sep
is a single space.
>>> print("hello", "world")
hello world
Changing sep
has the expected result.
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str()
. Passing an iterable to the print statement will stringify the iterable as one argument.
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep
.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join
as an alternative
The alternative approach for joining an iterable into a string with a given separator is to use the join
method of a separator string.
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
Solution 2
You can use str.join()
and create the string you want to print and then print it. Example -
print(','.join([str(x) for x in range(5)]))
Demo -
>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4
I am using list comprehension above, as that is faster than generator expression , when used with str.join
.
Solution 3
To do that, you can use str.join()
.
In [1]: print ','.join(map(str,range(5)))
0,1,2,3,4
We will need to convert the numbers in range(5)
to string first to call str.join()
. We do that using map()
operation. Then we join the list of strings obtained from map()
with a comma ,
.
Solution 4
Another form you can use, closer to your original code:
opt_comma="" # no comma on first print
for x in range(5):
print (opt_comma,x,sep="",end="") # we are manually handling sep and end
opt_comma="," # use comma for prints after the first one
print() # force new line
Of course, the intent of your program is probably better served by the other, more pythonic answers in this thread. Still, in some situations, this could be a useful method.
Another possibility:
for x in range(5):
if x:
print (", ",x,end="")
else:
print (x, end="")
print()
user2092743
Updated on February 17, 2022Comments
-
user2092743 over 2 years
I am writing a piece of code that should output a list of items separated with a comma. The list is generated with a
for
loop:for x in range(5): print(x, end=",")
The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:
0,1,2,3,4,
How do I remove the ending
,
? -
Ashwini Chaudhary almost 9 yearsYou meant
*range(5)
? -
Graeme Stuart almost 9 years
str.join()
would be a good option for generating a custom string from data. However, if we are only passing the string toprint()
then it is not necessary. Just useprint(*iterable, sep=", ")
. -
user2092743 almost 9 yearsThanks for the response! The problem is that I do need a loop, the code I provided above is simplefied code. I came with a solution myself just when I posted the question. I made a string variable where I kept adding strings to with a comma and when the loop did its last run, I made an if statement to not add a comma to my variable (where I pasted all the strings to)
-
Graeme Stuart almost 9 yearsNo problem, It may still simplify your code somewhat to generate an iterable (a list?) with your loop and then use print to render it to the console. No need for an intervening string to hold the commas.
-
Graeme Stuart almost 9 yearsThe "loop to concatenate with an if statement" approach is very clumsy. I would go with either
print(*iterable, sep=",")
orprint(",".join([str(i) for i in iterable]))
. -
tripleee over 3 yearsThis is clunky in this particular case, but a very useful technique in more complex cases when you want to have a separator between but not before or after something that you slowly loop your way through.
-
General Grievance over 2 yearsRelying on
\b
to overwrite output is terminal-specific. It will also not overwrite if output is redirected to a file. -
General Grievance over 2 yearsI get what you were going for with
5-1
, but it's still a number constant. Would be better to save the list size as a variable then re-use.