Convert a List of Characters into a String in Python

Let's say you have a list of individual characters, like this:

chars = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

What if you need to convert this list of characters into a string? In cases like this, you can use the join method.

>>> chars = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> ''.join(chars)
'hello world'

Note that the join method works on the string you want to use as the separator, not the array. This is different from other languages, like JavaScript, which uses the join method on the array. This is why we use call join on an empty string, we don't actually want the individual characters to be separated by anything.

If you want to separate the characters by something, and not just an empty string, use that character as the separator:

>>> chars = ['0', '1', '2', '3', '4']
>>> ','.join(chars)

But what if your list of characters contains non-string objects, like integers? In that case, Python will throw an error unless you explicitly convert the integers to strings.

>>> ','.join([1, 2, 3, 4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

If you have integers (or other data types) like this, first convert them to strings. This can be done in one line using the map function, which will call a method on each item in the list and return the modified array.

Here we first show how the map function works:

>>> integers = [1, 2, 3, 4]
>>> map(str, integers)
['1', '2', '3', '4']

And now, putting it all together with join:

>>> integers = [1, 2, 3, 4]
>>> ','.join(map(str, integers))

For another example, let's say you need to generate a template that has numbered lines for a worksheet printout. You could achieve this using range, map, and join:

>>> numbers = range(1,11)
>>> ')\n'.join(map(str, numbers)) + ')'

Formatted properly, the output would look like this:

Last Updated: April 10th, 2023
Was this helpful?

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup

Ā© 2013-2024 Stack Abuse. All rights reserved.