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.
Syntax:
str.split(separator)
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.split()
method
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.
Example:
import re
str = 'I am a programmer'
split_str = re.split('s+', str)
print(split_str) // ['I', 'am', 'a', 'programmer']
Here, re.split()
splits the string into a list of substrings.
s
it represents whitespace in regular expression.
The +
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.
Related Topics:
Split String and get the first element using python
How to split a list into multiple lists using Python
Replace a character in String by index in Python
Python – Check if a string is Empty or Not
Python – Remove Newline From Strings (3 Ways)