Convert a list of characters into a string


If I have a list of chars:

a = ['a','b','c','d']

How do I convert it into a single string?

a = 'abcd'
5/2/2013 9:44:52 AM

Accepted Answer

Use the join method of the empty string to join all of the strings together with the empty string in between, like so:

>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
12/19/2010 5:20:50 AM

This works in JavaScript or Ruby, why not in Python?

>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

But in Python the join method is on the str class:

# this is the Python way

It is a little weird, isn't it? Why join is not a method in the list object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list) method means: join the list into a new string using str as a separator (in this case str is an empty string).

Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow