How do you create comma separated strings from a list of strings?

Which is the best way to connect strings in a sequence so that you can add a comma between each two consecutive pairs. That is, how do you map, for example ['a ',' B ',' C '] to' a,b,c '? (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 I'm not satisfied with it.

#1 building

To convert a list that contains numbers:

string  =  ''.join([str(i) for i in list])

#2 building

This is an alternative solution to allow non string list items in Python 3.0:

>>> alist = ['a', 1, (2, 'b')]
  • Standard mode

    >>> ", ".join(map(str, alist)) "a, 1, (2, 'b')"
  • Alternative solutions

    >>> import io >>> s = io.StringIO() >>> print(*alist, file=s, sep=', ', end='') >>> s.getvalue() "a, 1, (2, 'b')"

Note: spaces after commas are intended.

#3 building

. join(l) is not applicable in all cases. I recommend using the CSV module with StringIO

import StringIO
import csv

l = ['list','of','["""crazy"quotes"and\'',123,'other things']

line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'

#4 building

This is an example of a list

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

More accurate:-

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

Example 2:

myList = ['Apple','Orange']
myList = ','.join(map(str, myList)) 
print "Output:", myList
Output: Apple,Orange

#5 building

>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

My list can contain any type of variable. This avoids the result 'A,,,D,E'.

Keywords: Lambda Python

Added by paparts on Wed, 22 Jan 2020 16:03:17 +0200