Split string by whitespace in python
📋 Table Of Content
In this post, we will learn how to split a string by spaces in python.
To split a string by whitespace in python we can use the
split() method. It splits a string and returns us a list containing the individual words from the string.
We can specify the separator in the split method. By default, the separator is any whitespace (
Split string in python
Let's see an example of the
str = "I am a programmer" split_str = str.split() print(split_str)
The output is:
['I', 'am', 'a', 'programmer']
Here, we have called the
split() method on the string. And since we have not passed any separator in the method, so by default, it split the given string by whitespace and returned us a list.
We can also use Regular expressions for this task too.
Using RegEx to split a string
To use RegEx in python we have to import the Regular Expression module (
re). It also provides a pre-defined
split() method that we can use to split a string by its spaces.
import re str = 'I am a programmer' split_str = re.split('\s+', str) print(split_str) // ['I', 'am', 'a', 'programmer']
re.split() splits the string into a list of substrings.
\s it represents whitespace in regular expression.
+ sign is use to match all whitespaces in the given string.
Even though the regular expression method is overkill for such a small task. But it's still better to know.