Python - split string with 1 or more space between words

0 points
Created by:

In this article, we would like to show you how to split a string with one or more spaces between words in Python.

Practical example

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 \s).

See also

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂