Convert a list of characters into a string

PythonString

Python Problem Overview


If I have a list of chars:

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

How do I convert it into a single string?

a = 'abcd'

Python Solutions


Solution 1 - Python

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)
'abcd'

Solution 2 - Python

This works in many popular languages like JavaScript and 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'

Strange enough, in Python the join method is on the str class:

# this is the Python way
"".join(['a','b','c','d'])

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.

Solution 3 - Python

If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join() available as a method on any old string object, and you will instead need to use the string module. Example:

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

try:
    b = ''.join(a)

except AttributeError:
    import string
    b = string.join(a, '')

The string b will be 'abcd'.

Solution 4 - Python

This may be the fastest way:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'

Solution 5 - Python

The reduce function also works

import operator
h=['a','b','c','d']
reduce(operator.add, h)
'abcd'

Solution 6 - Python

If the list contains numbers, you can use map() with join().

Eg:

>>> arr = [3, 30, 34, 5, 9]
>>> ''.join(map(str, arr))
3303459

Solution 7 - Python

h = ['a','b','c','d','e','f']
g = ''
for f in h:
    g = g + f

>>> g
'abcdef'

Solution 8 - Python

besides str.join which is the most natural way, a possibility is to use io.StringIO and abusing writelines to write all elements in one go:

import io

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

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

prints:

abcd

When using this approach with a generator function or an iterable which isn't a tuple or a list, it saves the temporary list creation that join does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.

Solution 9 - Python

You could also use operator.concat() like this:

>>> from operator import concat
>>> a = ['a', 'b', 'c', 'd']
>>> reduce(concat, a)
'abcd'

If you're using Python 3 you need to prepend:

>>> from functools import reduce

since the builtin reduce() has been removed from Python 3 and now lives in functools.reduce().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnosView Question on Stackoverflow
Solution 1 - PythonDaniel StutzbachView Answer on Stackoverflow
Solution 2 - PythonPaulo ScardineView Answer on Stackoverflow
Solution 3 - PythonKyleView Answer on Stackoverflow
Solution 4 - PythonbigeagleView Answer on Stackoverflow
Solution 5 - PythoncceView Answer on Stackoverflow
Solution 6 - PythonyaskView Answer on Stackoverflow
Solution 7 - PythonBillView Answer on Stackoverflow
Solution 8 - PythonJean-François FabreView Answer on Stackoverflow
Solution 9 - PythonTonechasView Answer on Stackoverflow