Explain Codes LogoExplain Codes Logo

Convert a list of characters into a string

python
join
iterables
string-concatenation
Alex KataevbyAlex Kataev·Feb 2, 2025
TLDR

Use join() method for converting a character list into a string:

chars = ['P', 'y', 't', 'h', 'o', 'n'] result = ''.join(chars) print(result) # Outputs: "Python"

Here, ''.join(chars) smoothly blends the characters in chars into one cohesive string, "Python".

Detailed look at join()

str.join() method is a shiny tool to glue parts of an iterative together. A great thing about it is the absence of separators between items, leading to a lusciously continuous string. Not to mention, it makes no fuss working with any iterable of strings, not just limited to character lists.

:::note When dealing with non-character iterables, remember to pack them as strings before inviting .join() to the party. :::

Backup dancers: Alternative methods

Sometimes, it's a different kind of show. .join() might be taking a day off, or just not the right one for the job. No worries, we have stand-ins:

The array module: Like numbers?

Sometimes, number lists fancy themselves as characters, ASCII values do that! Use the array module for their quick change costume:

from array import array chars = [80, 121, 116, 104, 111, 110] # Psst, they're ASCII for "Python". result = array('B', chars).tobytes().decode() print(result) # Tada: "Python"

Making reduce great again!

In a world where join is not an option, let's give reduce a chance:

from functools import reduce chars = ['P', 'y', 't', 'h', 'o', 'n'] # Our unsuspecting characters. result = reduce(lambda x, y: x+y, chars) # Lambda, the unsung hero. print(result) # The big reveal: "Python"

In this thriller, reduce takes them one by one, until we're left with our one true string. Plot twist!

Three's a crowd: When join is the third wheel

In some scenarios, join might be more a third wheel than a wingman. Let's explore:

Extra cheese: Prepending or appending fixed characters

If you're looking to add some flair to each character, join is your maestro:

chars = ['1', '2', '3'] result = ','.join(chars) print(result) # Echoes: "1,2,3"

The result? A classy comma-separated drama, perfect for a CSV banquet.

The race of performance

If it's a race and the list is long, join can be your Usain Bolt. It's often quicker and leaner than its rivals, especially when opposed against '+' in a loop, which ends up more like me on a treadmill, out of breath.

Hide and seek with non-string iterables

Let's say we're dealing with numbers pretending to be characters. Just make sure they're done with their make-up first:

numbers = [1, 2, 3] result = ''.join(str(number) for number in numbers) # Undercover as strings. print(result) # "123"

Here, we go undercover with generator expressions to infiltrate join()'s party.