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)

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

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: July 2nd, 2022
Was this helpful?

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic

© 2013-2022 Stack Abuse. All rights reserved.