688

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
mweerden
  • 13,619
  • 5
  • 32
  • 32
  • Does this answer your question? [How to concatenate items in a list to a single string?](https://stackoverflow.com/questions/12453580/how-to-concatenate-items-in-a-list-to-a-single-string) – Georgy Dec 09 '20 at 12:07

15 Answers15

1282
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)) 
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
  • 1
    Note if you are using python 2.7 (which you shouldn't by now) then using str will raise an exception if any item in the list has unicode. – kroiz May 26 '20 at 13:54
  • My requirement, bringing me here, was to fill an SQL "WHERE x NOT IN ()" clause. The join() function will insert any string you like between elements but does nothing for each end of the list. So this works: nameString = '"{}"'.format('", "'.join(nameList)) Those are single quotes enclosing the desired double quoted strings. Python 3.7 – Martin Bramwell Feb 12 '21 at 11:25
  • Why does python not have a professional function to perform this operation? – user2585501 Oct 07 '21 at 00:55
  • 1
    It's worth noting that this answer was posted over 13 years ago. I'm guessing plenty has changed with Python since then. – Mark Biek Oct 07 '21 at 12:56
92

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

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

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

In case if there are numbers in the list, you could use list comprehension:

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

or a generator expression:

>>> ','.join(str(x) for x in foo)
Georgy
  • 12,464
  • 7
  • 65
  • 73
jmanning2k
  • 9,297
  • 4
  • 31
  • 23
28

",".join(l) will not work for all cases. I'd suggest 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'
Ricky Sahu
  • 23,455
  • 4
  • 42
  • 32
17

Here is a alternative solution in Python 3.0 which allows non-string list items:

>>> alist = ['a', 1, (2, 'b')]
  • a standard way

    >>> ", ".join(map(str, alist))
    "a, 1, (2, 'b')"
    
  • the alternative solution

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

NOTE: The space after comma is intentional.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
17

@Peter Hoffmann

Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.

>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar' 
Aaron Maenpaa
  • 119,832
  • 11
  • 95
  • 108
  • Experts, please, tell why isn't this upvoted as the best solution? It works with integers, strings (with 'crazy characters' as well) and it's just 1 line of code. I'm newbie, so I'd like to know the limitations of this method. – Roman March Feb 20 '22 at 17:10
  • Hi, is there a way where I can let string literals remain as strings in this? – Mehar Fatima Khan Oct 27 '22 at 12:22
13

Don't you just want:

",".join(l)

Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

https://docs.python.org/library/csv.html

twasbrillig
  • 17,084
  • 9
  • 43
  • 67
Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137
10
>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

my_list may contain any type of variables. This avoid the result 'A,,,D,E'.

Shameem
  • 2,664
  • 17
  • 21
9
l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"
AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
  • 2
    I think you should point out that unlike the other solutions on this page, you quote strings as well. – mrdevlar Feb 23 '18 at 14:05
6

@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
Peter Hoffmann
  • 56,376
  • 15
  • 76
  • 59
  • This solution doesn't fulfill the requirements of not adding extra comma for empty string and adding a 'None' with NoneType. – Roberto Jan 07 '18 at 13:27
  • [check](https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python/9061024#9061024) `str.join` work faster with `list` in comparison to generator – Grijesh Chauhan Aug 07 '18 at 09:19
4

Here is an example with 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
4

If you want to do the shortcut way :) :

','.join([str(word) for word in wordList])

But if you want to show off with logic :) :

wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']
stringText = ''

for word in wordList:
    stringText += word + ','

stringText = stringText[:-2]   # get rid of last comma
print(stringText)
faiz-e
  • 190
  • 4
  • 21
1

Unless I'm missing something, ','.join(foo) should do what you're asking for.

>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'

(edit: and as jmanning2k points out,

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

is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the csv module, as Douglas points out in his answer.)

David Singer
  • 1,172
  • 1
  • 10
  • 11
1

I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.

To output a list l to a .csv file:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(l)  # this will output l as a single row.  

It is also possible to use writer.writerows(iterable) to output multiple rows to csv.

This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.

Ron Kalian
  • 3,280
  • 3
  • 15
  • 23
0

mmm also need for SQL is :

l = ["foo" , "baar" , 6]
where_clause = "..... IN ("+(','.join([ f"'{x}'" for x in l]))+")"
>> "..... IN ('foo','baar','6')"

enjoit

-1

My two cents. I like simpler an one-line code in python:

>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'

It's pythonic, works for strings, numbers, None and empty string. It's short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:

>>> ','.join(ifilter(lambda x: x, l))

Also this solution doesn't create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).

Roberto
  • 374
  • 6
  • 9
  • 1
    This is superfluous. The accepted answer is simple, direct and clearly the best solution. To provide overly complex alternatives is a pointless waste of time. If you're merely trying to educate about other features of the language when there is already a viable answers, you're doing the same thing you downvoted me for. – clearlight Feb 25 '18 at 15:24