tags:

views:

5347

answers:

4

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', ' ', .....]
A: 

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...

rossp
with an extra space that doesn't exist at the end...
Mez
I've just updated this code to remove the final space. That said, it's still not the best way to do it, just *a* way to do it :)
rossp
+32  A: 
>>> 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.

Greg Hewgill
This is a cleaner solution than the one I posted above.
rossp
+3  A: 

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")
Mez
A: 

Not that I can see from the documentation, but if you use split(' '), then you will get blank elements for multiple spaces. You can then reconstitute the spaces into the list afterwards.

Chris Jester-Young