tags:

views:

2996

answers:

9

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

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

I'm pretty sure that doesn't work if the list contains numbers.

Mark Biek
you are right, it won't work if the list contains numbers, but this way it will: myList = ','.join(map(str, myList))
Ricardo Reyes
Ah great! I will use map() in the future. I have always done:myString = ",".join([str(x) for x in myList])
kigurai
+4  A: 

Why the map/lamda 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)
jmanning2k
+5  A: 

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:

http://docs.python.org/lib/module-csv.html

Douglas Leeder
+2  A: 

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
+3  A: 

@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
+2  A: 

@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
A: 

>>> l=['a', 1, 'b', 2]

>>>print str(l)[1:-1]

"'a', 1, 'b', 2"

A: 

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.

J.F. Sebastian
A: 

What if you want to concatenate strings excluding empty values? For example:

>>> mylist = ('aaa', '', 'ccc')

What I would like to obtain is a string that excludes values of the string that are empty, so:

>>> 'aaa, ccc'

instead of what ', '.join(mylist) does, which is

>>> 'aaa, , ccc'

Is there an easy way?

gozzilli