2

Does exist a command such that splits a string in a way that the whitespaces become a string too?. For example, suppose that the command is "coolsplit":

>>> example='hey,    whats up,     how are you?'
>>> example.coolsplit()
    ['hey,','   ','whats',' ','up,','     ','how',' ','are',' ','you?'] 

Does it exist?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
iam_agf
  • 639
  • 2
  • 9
  • 20

1 Answers1

5

You can do re.split() capturing the delimiter:

>>> import re
>>>
>>> re.split(r'(\s+)', example)
['hey,', '    ', 'whats', ' ', 'up,', '     ', 'how', ' ', 'are', ' ', 'you?']

\s+ here means "one or more whitespace characters", parenthesis define a saving group.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195