user2177047 user2177047 -5 years ago 128
Python Question

Split string at word boundaries without losing whitespaces or newlines

Suppose I have a string like this which contains (multiple) whitespaces and newlines:

"\n\n\nmy string \n"

I want this to be split into:

['\n', '\n', '\n', 'my', ' ', ' ', 'string', ' ', '\n']

How could I get this? I suppose I need a regular expression?

Answer Source

Use regex \w+|\W and find matches

>>> import re
>>> p = re.compile('\w+|\W')
>>> p.findall('\n\n\nmy  string \n')

['\n', '\n', '\n', 'my', ' ', ' ', 'string', ' ', '\n']

Regex explanation here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download