Question

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+....)

Was it helpful?

Solution

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:

myList = ','.join(map(str, myList)) 

OTHER TIPS

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

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)

",".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'

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.

@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' 

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

>>> 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'.

@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))

for converting list containing numbers do the following:

string  =  ''.join([str(i) for i in list])
l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"

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.)

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

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.

just a little something like this :)

String = "Once:Upon:a:Time:A:Long:Time:Ago"
ding = String.split(':')

ring = (" , ").join(ding)

print(ring)

Output: Once , Upon , a , Time , A , Long , Time , Ago

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top