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


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' ] to 'a,b,c'? (The cases [ s ] and [] should be mapped to s and '', 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 s.join([e1,e2,...]) as a shorthand for s+e1+e2+....)

4/18/2018 5:54:07 PM

Accepted Answer

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

This won't work if the list contains numbers.

As Ricardo Reyes suggested, if it contains non-string types (such as integers, floats, bools, None) then do:

myString = ','.join(map(str, myList)) 
6/28/2019 6:19:22 PM

Why the map/lambda magic? Doesn't this work?

>>>foo = [ 'a', 'b', 'c' ]
>>>print ",".join(foo)
>>>print ",".join([])

>>>print ",".join(['a'])

Edit: @mark-biek points out the case for numbers. Perhaps the list comprehension:

>>>','.join([str(x) for x in foo])

is more "pythonic".

Edit2: Thanks for the suggestions. I'll use the generator rather than the list comprehension in the future.

>>>','.join(str(x) for x in foo)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow