Convert a List of Characters into a String in Python

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)
'0,1,2,3,4'

But what if your list of characters contains non-string objects, like integers? In that case, Python will throw an error unless you explicity 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))
'0,1,2,3,4'

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)) + ')'
'1)\n2)\n3)\n4)\n5)\n6)\n7)\n8)\n9)\n10)'

Formatted properly, the output would look like this:

1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
Last Updated: July 2nd, 2022
Was this helpful?
Project

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
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

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

DisclosurePrivacyTerms