mweerden mweerden - 2 years ago 123
Python Question

How would you make a comma-separated string from a list?

What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance,

[ 'a', 'b', 'c' ]
? (The cases
[ s ]
should be mapped to
, respectively.)

I usually end up using something like
''.join(map(lambda x: x+',',l))[:-1]
, but also feeling somewhat unsatisfied.

Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised
as a shorthand for

Answer Source
myList = ['a','b','c','d']
myString = ",".join(myList )

This won't work if the list contains numbers.

As Ricardo Reyes suggested, if it contains numbers then do:

myList = ','.join(map(str, myList)) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download