Languages
[Edit]
EN

Python - split string with 1 or more space between words

0 points
Created by:
Khloe-Kaiser
398

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']

Output:

['split', 'this', 'text', 'into', 'words']

Note:

  • \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

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.

❤️💻 🙂

Join