How to split string on whitespace in Python?


In this article, we are going to find out how to split a string on whitespace in Python.

The first approach is by using the inbuilt method split(). This method splits the given string at our desired delimiter. The split() method accepts a parameter named as a delimiter, it specifies at what character should a string be split.

So, we have to send white space as a delimiter to the split() method. This method returns the modified list that is split in white space.

Example

In the example given below, we are taking a string as input and we are splitting the string at whitespaces using split() method 

str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = str1.split()
print(res)

Output

The output of the above example is given below −

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

Using re.split() function

Regular expressions are used in the second technique. Import the re library and install it if it isn't already installed to use it. After importing the re library, we can use the regular expression 's+' in the re.split() function. The re.split() function takes the regular expression and the string as parameters and splits the string at characters that are specified by the regular expression.

Example

In the example given below, we are taking a string as input and we are splitting the string at whitespace using regular expressions 

import re
str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = re.split('\s+', str1)
print(res)

Output

The output of the above example is as shown below −

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

Using re.findall() function

The third approach is by using the re.findall() method of Regular Expressions. This method finds all the strings that are not spaces, so technically it splits the string at whitespaces.

Example

In the example given below, we are taking a string as input and we are splitting the string at whitespace using re.findall() method 

import re
str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = re.findall(r'\S+', str1)
print(res)

Output

The output of the above example is as shown below −

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

Updated on: 07-Dec-2022

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements