Magnus Teekivi
Magnus Teekivi

Reputation: 493

Split string into list of non-whitespace and whitespace

I want to split a string into parts so that

Hello,  what   is up?

becomes

["Hello,", "  ", "what", "   ", "is", " ", "up?"]

Upvotes: 3

Views: 2054

Answers (2)

vks
vks

Reputation: 67968

import re
x="Hello,  what   is up?"
print re.split("(\s+)",x)

You can use re.split for this.

Output:['Hello,', ' ', 'what', ' ', 'is', ' ', 'up?']

We can also use

re.findall(r"\S+|\s+",x)

This will not give empty string is there's a space at start or end.

Upvotes: 11

nagato
nagato

Reputation: 93

Simply use string.split(" ").If you want to eliminate those white spaces also then string.split()

Upvotes: -4

Related Questions