Python | Split String Variable Spaces

Summary: The most efficient way to split a string using variable spaces is to use the split function like so given_string.split(). An alternate approach is to use different functions of the regex package to split the string at multiple whitespaces.

Minimal Example

text = "a   b  c      d"
# Method 1
print(text.split())
# Method 2
import re
print(re.split('\s+', text))
# Method 3
print([x for x in re.findall(r'\S+', text) if x != ''])
# Method 4
print(re.sub(r'\s+', ',', text).split(','))
# Method 5
print(list(filter(None, text.split())))

# ['a', 'b', 'c', 'd']

Problem Formulation

📜Problem: Given a string. How will you split the string using multiple spaces?

Example

# Input
text = "abc   xyz  lmn pqr"
# Output
['abc', 'xyz', 'lmn', 'pqr']

The given input has multiple spaces between each substring, i.e., there are three spaces after abc, two spaces after xyz while a single space after lmn. So, not only do you have multiple spaces between the substring but also varied number of spaces. Can you split the string by varied and multiple spaces?


Though the question might look daunting at first but once you get hold of it, the solutions to this problem are easier than one can imagine. So, without further delay let us dive into the different ways of solving the given problem.

Method 1: Using split()

The built-in split('sep') function allows you to split a string in Python based on a given delimiter. By default the split function splits a given string at whitespaces. Meaning, if you do not pass any delimiter to the split function then the string will be split at whitespaces.

You can use this default property of the split function and successfully split the given string at multiple spaces just by using the split() function.

Code:

text = "abc   xyz  lmn pqr"
print(text.split())

# ['abc', 'xyz', 'lmn', 'pqr']

📚Recommended DigestPython String split()

Method 2: Using re.split

The re.split(pattern, string) method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, re.split('a', 'bbabbbab') results in the list of strings ['bb', 'bbb', 'b'].

Approach: To split the string using multiple space characters use re.split("\s+", text) where \s+ is the matching pattern and it represents a special sequence that returns a match whenever it finds any whitespace character and splits the string. So, whenever there’s a space or multiple spaces (any number of occurrences of space are whitespace characters) the string will be split.

Code:

import re
text = "abc   xyz  lmn pqr"
print(re.split('\s+', text))
# ['abc', 'xyz', 'lmn', 'pqr']

📚Recommended Read:  Python Regex Split.

Method 3: Using re.findall

The re.findall(pattern, string) method scans the string from left to right, searching for all non-overlapping matches of the pattern. It returns a list of strings in the matching order when scanning the string from left to right.

📚Recommended Read: Python re.findall() – Everything You Need to Know

Code:

import re
text = "abc   xyz  lmn pqr"
print([x for x in re.findall(r'\S+', text) if x != ''])
# ['abc', 'xyz', 'lmn', 'pqr']

Method 4: Using re.sub

The regex function re.sub(P, R, S) replaces all occurrences of the pattern P with the replacement R in string S. It returns a new string. For example, if you call re.sub('a', 'b', 'aabb'), the result will be the new string 'bbbb' with all characters 'a' replaced by 'b'.

Approach: Use the re.sub method to replace all occurrences of space characters in the given string with a comma. Thus, the string will now have commas instead of space characters and you can simply split it using a normal string split method by passing comma as the delimiter.

Silly! Isn’t it? Nevertheless, it works.

Code:

import re
text = "abc   xyz  lmn pqr"
res = re.sub(r'\s+', ',', text).split(',')
print(res)
# ['abc', 'xyz', 'lmn', 'pqr']

Method 5: Using filter

Python’s built-in filter() function filters out the elements that pass a filtering condition. It takes two arguments: function and iterable. The function assigns a Boolean value to each element in the iterable to check whether the element will pass the filter or not. It returns an iterator with the elements that pass the filtering condition.

📚Related Read: Python filter()

Approach: You can use the filter() method to split the string by space. Feed in None as the first argument and the list of split strings as the second argument into the filter function. The filter() function then iterates through the list and filters out the spaces from the given string and returns only the non-whitespace characters. As the filter() method returns an object, we need to use the list() constructor to convert the object into a list.

Code:

text = "abc   xyz  lmn pqr"
print(list(filter(None, text.split())))
# ['abc', 'xyz', 'lmn', 'pqr']

Conclusion

Hurrah! We have successfully solved the given problem using as many as five different ways. I hope you enjoyed reading this article and it helped you in your Python coding journey. Please subscribe and stay tuned for more interesting articles!

Happy coding! 🙂

📚Suggested Read: Python Regex Superpower [Full Tutorial]


Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.