Skip to content
Advertisement

python split a string with at least 2 whitespaces

I would like to split a string only where there are at least two or more whitespaces.

For example

str = '10DEUTSCH        GGS Neue Heide 25-27     Wahn-Heide   -1      -1'
print(str.split())

Results:

['10DEUTSCH', 'GGS', 'Neue', 'Heide', '25-27', 'Wahn-Heide', '-1', '-1']

I would like it to look like this:

['10DEUTSCH', 'GGS Neue Heide 25-27', 'Wahn-Heide', '-1', '-1']

Advertisement

Answer

>>> import re    
>>> text = '10DEUTSCH        GGS Neue Heide 25-27     Wahn-Heide   -1      -1'
>>> re.split(r's{2,}', text)
['10DEUTSCH', 'GGS Neue Heide 25-27', 'Wahn-Heide', '-1', '-1']

Where

  • s matches any whitespace character, like tnrfv and more
  • {2,} is a repetition, meaning “2 or more”
Advertisement