Question

Is there a function in Python to split a string without ignoring the spaces in the resulting list?

E.g:

s="This is the string I want to split".split()

gives me

>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']

I want something like

['This',' ','is',' ', 'the',' ','string', ' ', .....]
Was it helpful?

Solution

>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']

Using the capturing parentheses in re.split() causes the function to return the separators as well.

OTHER TIPS

I don't think there is a function in the standard library that does that by itself, but "partition" comes close

The best way is probably to use regular expressions (which is how I'd do this in any language!)

import re
print re.split(r"(\s+)", "Your string here")

Silly answer just for the heck of it:

mystring.replace(" ","! !").split("!")

The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.

Perhaps this may help:

s = "String to split"
mylist = []
for item in s.split():
    mylist.append(item)
    mylist.append(' ')
mylist = mylist[:-1]

Messy, but it'll do the trick for you...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top