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
  • 561,645
  • 34
  • 376
  • 476
iam_agf
  • 571
  • 2
  • 8
  • 19

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
  • 441,113
  • 110
  • 1,021
  • 1,148