How to Convert a String to a List of Characters in Python?

Learn how to split a string into a list of characters in Python

In Python, there are several ways in which you can convert a string to a list of characters. Some of these are as follows:

Using List Comprehension

You can use list comprehension to split a string into a list of characters, for example, like so:

str = 'foo bar'
chars = [char for char in str]
print(chars) # ['f', 'o', 'o', ' ', 'b', 'a', 'r']

This is essentially equivalent to using list() (to achieve the same) in terms of functionality. However, list comprehension may be slightly faster in terms of execution time, since it's a more concise and "Pythonic" way of expressing the same operation.

That being said, the difference in performance is usually not that significant, unless you are working with very large strings or are performing the operation in a loop. In most cases, you should choose the approach that is most readable and maintainable for your codebase.

Using list()

You can convert a Python string to a list of characters by using the list() method, for example, like so:

str = 'foo bar'
chars = list(str)
print(chars) # ['f', 'o', 'o', ' ', 'b', 'a', 'r']

Unpacking

Starting with Python 3.5, you can also "unpack" the elements of an iterable object (such as a string) into separate elements of a list (by using the * operator), for example, like so:

# Python 3.5+
str = 'foo bar'
chars = [*str]
print(chars) # ['f', 'o', 'o', ' ', 'b', 'a', 'r']

Using extend()

Since a string is an iterable, you can use the extend() method, which iterates over its argument and adds each element to the list:

str = 'foo bar'
chars = []
chars.extend(str)
print(chars) # ['f', 'o', 'o', ' ', 'b', 'a', 'r']

This can also be shortened using the l += s syntax (which is essentially the same as l.extend(s)), for example, like so:

str = 'foo bar'
chars = []
chars += str
print(chars) # ['f', 'o', 'o', ' ', 'b', 'a', 'r']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.