12-07-2022, 06:41 AM
Python | Split String Variable Spaces
Rate this post
Summary: The most efficient way to split a string using variable spaces is to use the function like so . An alternate approach is to use different functions of the regex package to split the string at multiple whitespaces.
[b]Minimal Example[/b]
[b]Problem Formulation[/b]
Problem: Given a string. How will you split the string using multiple spaces?
[b]Example[/b]
The given input has multiple spaces between each substring, i.e., there are three spaces after, two spaces after while a single space after . 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 function allows you to split a string in Python based on a given delimiter. By default the 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 function.
Code:
Recommended Digest: Python String split()
Method 2: [b]Using re.split[/b]
The method matches all occurrences of the in the and divides the string along the matches resulting in a list of strings between the matches. For example, results in the list of strings .
Approach: To split the string using multiple space characters use where 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:
Recommended Read: [b]Python Regex Split.[/b]
[b]Method 3: Using re.findall[/b]
The method scans the from left to right, searching for all non-overlapping matches of the . 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:
[b]Method 4: Using re.sub[/b]
The regex function replaces all occurrences of the pattern with the replacement in string . It returns a new string. For example, if you call , the result will be the new string with all characters replaced by .
Approach: Use the 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:
Method 5: Using filter
Python’s built-in 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 method to split the string by space. Feed in as the first argument and the list of split strings as the second argument into the function. The function then iterates through the list and filters out the spaces from the given string and returns only the non-whitespace characters. As the method returns an object, we need to use the to convert the object into a list.
Code:
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!![[Image: 1f642.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png)
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.
Rate this post
Summary: The most efficient way to split a string using variable spaces is to use the Code:
splitCode:
given_string.split()[b]Minimal Example[/b]
Code:
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: Given a string. How will you split the string using multiple spaces?[b]Example[/b]
Code:
# 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
Code:
abcCode:
xyzCode:
lmnThough 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
Code:
split('sep')Code:
splitYou can use this default property of the split function and successfully split the given string at multiple spaces just by using the
Code:
split()Code:
Code:
text = "abc xyz lmn pqr"
print(text.split()) # ['abc', 'xyz', 'lmn', 'pqr']
Recommended Digest: Python String split()Method 2: [b]Using re.split[/b]
The
Code:
re.split(pattern, string)Code:
patternCode:
stringCode:
re.split('a', 'bbabbbab')Code:
['bb', 'bbb', 'b']Approach: To split the string using multiple space characters use
Code:
re.split("\s+", text)Code:
\s+Code:
Code:
import re
text = "abc xyz lmn pqr"
print(re.split('\s+', text))
# ['abc', 'xyz', 'lmn', 'pqr']
Recommended Read: [b]Python Regex Split.[/b][b]Method 3: Using re.findall[/b]
The
Code:
re.findall(pattern, string)Code:
stringCode:
pattern
Recommended Read: Python re.findall() – Everything You Need to KnowCode:
Code:
import re
text = "abc xyz lmn pqr"
print([x for x in re.findall(r'\S+', text) if x != ''])
# ['abc', 'xyz', 'lmn', 'pqr']The regex function
Code:
re.sub(P, R, S)Code:
PCode:
RCode:
SCode:
re.sub('a', 'b', 'aabb')Code:
'bbbb'Code:
'a'Code:
'b'Approach: Use the
Code:
re.subSilly! Isn’t it? Nevertheless, it works.
Code:
Code:
import re
text = "abc xyz lmn pqr"
res = re.sub(r'\s+', ',', text).split(',')
print(res)
# ['abc', 'xyz', 'lmn', 'pqr']Python’s built-in
Code:
filter()
Related Read: Python filter()Approach: You can use the
Code:
filter()Code:
NoneCode:
filterCode:
filter()Code:
filter()Code:
list()Code:
Code:
text = "abc xyz lmn pqr"
print(list(filter(None, text.split())))
# ['abc', 'xyz', 'lmn', 'pqr']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!
![[Image: 1f642.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png)
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.

