Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 every two consecutive pairs 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.

like image 920
mweerden Avatar asked Sep 04 '08 21:09

mweerden


People also ask

How do you make a comma-separated string into a list in Python?

You can use the str. split method. Careful though, splitting an empty string does not return what one might have expected: "". split(",") returns [""] (a list with one element, which is empty string).

How do I convert a list to a comma-separated string in Excel?

Please follow these instructions: 1. Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)


1 Answers

my_list = ['a', 'b', 'c', 'd'] my_string = ','.join(my_list) 
'a,b,c,d' 

This won't work if the list contains integers


And if the list contains non-string types (such as integers, floats, bools, None) then do:

my_string = ','.join(map(str, my_list))  
like image 140
Mark Biek Avatar answered Sep 20 '22 04:09

Mark Biek