Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

split

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', ' ', .....]
like image 409
gath Avatar asked Sep 22 '08 07:09

gath


2 Answers

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

like image 175
Greg Hewgill Avatar answered Oct 07 '22 19:10

Greg Hewgill


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")
like image 34
Mez Avatar answered Oct 07 '22 18:10

Mez