Split a string into a list of characters in Python

avatar

Borislav Hadzhiev

Thu Jun 23 20222 min read

banner

Photo by Kym Ellis

Split a string into a list of characters in Python #

Use the list() class to split a string into a list of characters, e.g. my_list = list(my_str). The list() class will convert the string into a list of characters.

main.py
my_str = 'apple' my_list = list(my_str) print(my_list) # 👉️ ['a', 'p', 'p', 'l', 'e']

The list class takes an iterable and returns a list object.

When a string is passed to the class, it splits the string on each character and returns a list containing the characters.

An alternative approach is to use a list comprehension.

Use a list comprehension to split a string into a list of characters, e.g. my_list = [char for char in my_str]. List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

main.py
my_str = 'apple' my_list = [char for char in my_str] # 👇️ ['a', 'p', 'p', 'l', 'e'] print(my_list)

You can also filter characters out of the final list when using this approach.

main.py
my_str = 'a p p l e' my_list = [char for char in my_str if char.strip()] # 👇️ ['a', 'p', 'p', 'l', 'e'] print(my_list)

The string in the example has spaces.

Instead of getting list items that contain a space, we call the strip() method on each char and see if the result is truthy.

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

If the character is a space, it would get excluded from the final list.

You can also use a simple for loop to split a string into a list of characters.

main.py
my_str = 'apple' my_list = [] for char in my_str: my_list.append(char) # 👇️ ['a', 'p', 'p', 'l', 'e'] print(my_list)

We used a for loop to iterate over the string and use the append method to add each character to the list.

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

You can also conditionally add the character to the list.

main.py
my_str = 'a p p l e' my_list = [] for char in my_str: if char.strip() != '': my_list.append(char) # 👇️ ['a', 'p', 'p', 'l', 'e'] print(my_list)

The string is only added to the list if it isn't a space.

Use the search field on my Home Page to filter through my more than 1,000 articles.