This post will discuss how to split a string on whitespace in Python. The result should be a list of words in the string but without any leading or trailing whitespace.

1. Using str.split() function

The Pythonic way of splitting on a string in Python uses the str.split(sep) function. It splits the string based on the specified delimiter sep. When the delimiter is not provided, the consecutive whitespace is treated as a separator.

This is demonstrated below, where the no-arg split function splits on whitespace:

Download  Run Code

2. Using Regular Expression

This can also be done using regular expressions. However, regular expressions are not considered very Pythonic and would be overkill for such a trivial task. Here’s a Python program that demonstrates it:

Download  Run Code

That’s all about splitting a string on whitespace in Python.