In this article, we would like to show you how to split a string with one or more spaces between words in Python.
In this example, we import
re module for regular expression (regex), so we can use
re.split() method to split the
text string with one or more white spaces between words.
import re text = "split this text into words" words = re.split(r'\s+', text) print(words) # ['split', 'this', 'text', 'into', 'words']
['split', 'this', 'text', 'into', 'words']
\s- matches any whitespace character (spaces, tabs, line breaks),
+- matches one or more of the preceding token (in our case two or more