Split string and remove whitespace in Python

avatar

Borislav Hadzhiev

Last updated: Jun 23, 2022

banner

Photo from Unsplash

Split string and remove whitespace in Python #

To split a string and remove whitespace:

  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, use the str.strip() method to remove the leading and trailing whitespace.
main.py
my_str = 'one, two, three, four' my_list = [word.strip() for word in my_str.split(',')] print(my_list) # 👉️ ['one', 'two', 'three', 'four']

We used the str.split() method to split the string on each occurrence of a comma.

The str.split() method splits the original 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.

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

The next step is to use a list comprehension to iterate over the list of strings.

main.py
my_str = 'one, two, three, four' my_list = [word.strip() for word in my_str.split(',')] print(my_list) # 👉️ ['one', 'two', 'three', 'four']
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 call the str.strip() method to remove any leading or trailing whitespace from the string.

main.py
example = ' hello ' print(repr(example.strip())) # 👉️ 'hello'

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

An alternative approach is to use the map() function.

To split a string and remove whitespace:

  1. Call the str.split() method on the string to get a list of strings.
  2. Pass the str.strip method and the list to the map() function.
  3. The map function will call the str.strip method on each string in the list.
main.py
my_str = 'one, two, three, four' my_list = list(map(str.strip, my_str.split(','))) print(my_list) # 👉️ ['one', 'two', 'three', 'four']

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the str.strip method as the function, so the map function is going to call the str.strip() method on each item in the list.

The map function returns a map object (not a list). If you need to convert the value to a list, pass it to the list() class.

Which approach you pick is a matter of personal preference. I'd go with the list comprehension as it is a bit more readable and explicit.

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.