Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python | Split String Variable Spaces
1
Python | Split String Variable Spaces

Rate this post

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

[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']
[b]Problem Formulation[/b]

[Image: 1f4dc.png]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:
abc
, two spaces after
Code:
xyz
while a single space after
Code:
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
Code:
split('sep')
function allows you to split a string in Python based on a given delimiter. By default the 
Code:
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 
Code:
split()
 function.

Code:

Code:
text = "abc xyz lmn pqr" print(text.split()) # ['abc', 'xyz', 'lmn', 'pqr']

[Image: 1f4da.png]Recommended Digest: Python String split()

Method 2: [b]Using re.split[/b]

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

Approach: To split the string using multiple space characters use 
Code:
re.split("\s+", text)
 where 
Code:
\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:

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

[Image: 1f4da.png]Recommended Read:  [b]Python Regex Split.[/b]

[b]Method 3: Using re.findall[/b]

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

[Image: 1f4da.png]Recommended Read: Python re.findall() – Everything You Need to Know

Code:

Code:
import re text = "abc xyz lmn pqr" print([x for x in re.findall(r'\S+', text) if x != '']) # ['abc', 'xyz', 'lmn', 'pqr']
[b]Method 4: Using re.sub[/b]

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

Approach: Use the 
Code:
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:

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 
Code:
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.

[Image: 1f4da.png]Related Read: Python filter()

Approach: You can use the 
Code:
filter()
 method to split the string by space. Feed in
Code:
None
as the first argument and the list of split strings as the second argument into the
Code:
filter
function. The 
Code:
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 
Code:
filter()
 method returns an object, we need to use the 
Code:
list()
 to convert the object into a list.

Code:

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! [Image: 1f642.png]

[Image: 1f4da.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.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: