Sick Gaming
[Tut] Python | Split String Multiple Whitespaces - Printable Version

+- Sick Gaming (https://sickgaming.net)
+-- Forum: Programming (https://sickgaming.net/forum-76.html)
+--- Forum: Python (https://sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python | Split String Multiple Whitespaces (/thread-100350.html)



[Tut] Python | Split String Multiple Whitespaces - xSicKxBot - 12-06-2022

Python | Split String Multiple Whitespaces

Rate this post

[Image: 1f34e.png]Summary: The most efficient way to split a string using multiple whitespaces 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:
import re text = "mouse\nsnake\teagle human" # Method 1 print(text.split()) # Method 2 res = re.split("\s+", text) print(res) # Method 3 res = re.sub(r'\s+', ',', text).split(',') print(res) # Method 4 print(re.findall(r'\S+', text)) # ['mouse', 'snake', 'eagle', 'human']
[b]Problem Formulation[/b]

[Image: 1f4dc.png]Problem: Given a string. How will you split the string using multiple whitespaces?

[b]Example[/b]

Code:
# Input text = "abc\nlmn\tpqr xyz\rmno" # Output ['abc', 'lmn', 'pqr', 'xyz', 'mno']

There are numerous ways of solving the given problem. So, without further ado, let us dive into the solutions.

Method 1: Using Regex

The best way to deal with multiple delimiters is to use the flexibility of the regular expressions library. There are different functions available in the regex library that you can use to split the given string. Let’s go through each one by one.

[b]1.1 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']
.

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

Approach: To split the string using multiple whitespace 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.

Code:

Code:
import re text = "abc\nlmn\tpqr xyz\rmno" res = re.split("\s+", text) print(res) # ['abc', 'lmn', 'pqr', 'xyz', 'mno']
[b]1.2 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\nlmn\tpqr xyz\rmno" print(re.findall(r'\S+', text))

Explanation: In the expression, i.e.,
Code:
re.findall(r"\S'+", text)
, all occurrences of characters except whitespaces are found and stored in a list. Here,
Code:
\S+
returns a match whenever the string contains one or more occurrences of normal characters (characters from a to Z, digits from 0-9, etc. However, not the whitespaces are considered).

[b]1.3 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'
.

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

Code:

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

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.

Method 2: Using split()

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 whitespaces just by using the
Code:
split()
function.

Code:

Code:
text = "abc\nlmn\tpqr xyz\rmno" print(text.split()) # ['abc', 'lmn', 'pqr', 'xyz', 'mno']

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

Conclusion

We have successfully solved the given problem using different approaches. Simply using split could do the job for you. However, feel free to explore and try out the other options mentioned above. I hope this article helped you in your Python coding journey. Please subscribe and stay tuned for more interesting articles.

Happy Pythoning! [Image: 1f40d.png] 

Python Regex Course

Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages.  

Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages. 

Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions.  Regular expressions ​rule the game ​when text processing ​meets computer science. 

If you want to become a regular expression master too, check out themost comprehensive Python regex course on the planet:

[Image: ClickToPlay-1024x576.jpg]