Split string and ignore empty strings in Python

avatar

Borislav Hadzhiev

Last updated: Jun 23, 2022

banner

Photo from Unsplash

Split string and ignore empty strings in Python #

To split a string and ignore empty strings:

  1. Use the str.split() method to split the string into a list.
  2. Pass None as the first argument to the filter() function, and the list as the second.
  3. The filter() function will remove all empty strings from the list.
main.py
my_str = ',one,two,three,' my_list = list(filter(None, my_str.split(','))) print(my_list) # 👉️ ['one', 'two', 'three'] # Alternative (list comprehension) # 👇️ ['one', 'two', 'three'] print([word for word in my_str.split(',') if word])

We used the str.split() method to split the string into a list.

main.py
my_str = ',one,two,three,' # 👇️ ['', 'one', 'two', 'three', ''] print(my_str.split(','))

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If the separator is not found in the string, a list containing only 1 element is returned.

The next step is to use the filter() function to exclude all empty strings from the result.

main.py
my_str = ',one,two,three,' my_list = list(filter(None, my_str.split(','))) print(my_list) # 👉️ ['one', 'two', 'three']

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

If you pass None for the function argument, all falsy elements of the iterable are removed.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

Note that the filter() function returns a filter object (not a list). If you need to convert the object to a list, pass it to the list() class.

The default behavior of keeping empty strings after using str.split() is so that we are able to join the list into the same string, using the same delimiter.

main.py
my_str = ',one,two,three,' my_list = my_str.split(',') print(my_list) # 👉️ ['', 'one', 'two', 'three', ''] my_str_again = ','.join(my_list) print(my_str_again) # 👉️ ',one,two,three,'

If we remove the empty strings from the list and then join the list into a string, we would end up removing the leading and trailing commas.

main.py
my_str = ',one,two,three,' my_list = list(filter(None, my_str.split(','))) print(my_list) # 👉️ ['', 'one', 'two', 'three', ''] my_str_again = ','.join(my_list) print(my_str_again) # 👉️ 'one,two,three'

An alternative approach to split a string and ignore empty strings is to use a list comprehension.

To split a string and ignore empty strings:

  1. Use the str.split() method to split the string into a list.
  2. Use a list comprehension to iterate over the list.
  3. On each iteration, check if the list item is truthy to exclude empty strings from the result.
main.py
my_str = ',one,two,three,' my_list = [word for word in my_str.split(',') if word] print(my_list) # 👉️ ['one', 'two', 'three']

We used the str.split() method to split the string on each occurrence of a comma and a list comprehension to iterate over the list.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we simply check if the string is truthy, and since empty strings are not, we exclude them from the result.

Which approach you pick is a matter of personal preference. The list comprehension approach should be a little easier to read and more explicit if you aren't familiar with how the filter() function works when passed None as the first argument.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.