What would be the cleanest way to do comma separated printing on python for a list.
I have list: [1,2,3,4]
I need: "1, 2, 3, 4"
What would be the cleanest way to do comma separated printing on python for a list.
I have list: [1,2,3,4]
I need: "1, 2, 3, 4"
You can try to use map
to apply str
method to all the items to convert int
to str
and then use join
method to concatenate the list:
Concatenate a list or tuple of words with intervening occurrences of sep.
a=[1,2,3,4]
print ",".join(map(str,a))
Output:
1,2,3,4
The only unusual part is the ...
, which str
and repr
both unfortunately turn into 'Ellipsis'
. The other answers don't handle it correctly, but this one does:
>>> a = [1, 2, 3, 4, ...]
>>> print(', '.join('...' if x is ... else str(x) for x in a))
1, 2, 3, 4, ...
Edit: This is for the original question, before it was changed (though it still works).
You can do something on this line.
mylist = [1,2,3,4,5]
m = map(str, mylist) # map function to convert each item in the list to a string
j = ', '.join(m) # join to combine those strings with ', '
print (j)
Assuming you don't actually have ...
and don't actually want to print the quotes:
>>> a = [1, 2, 3, 4]
>>> print(*a, sep=', ')
1, 2, 3, 4
Or less clean:
>>> print(str(a)[1:-1])
1, 2, 3, 4