python - splitting a string without removing delimiters
Question: I'm trying to split a string without removing the delimiter and having trouble
doing so. The string I want to split is:

    
    
    '+ {- 9 4} {+ 3 2}'
    

and I want to end up with

    
    
    ['+', '{- 9 4}', '{+ 3 2}']
    

yet everything I've tried hasn't worked. I was looking through this
stackoverflow post for answers as well as google: [Python split() without
removing the delimiter](http://stackoverflow.com/questions/7866128/python-
split-without-removing-the-delimiter)

Thanks!


Answer: re.split will keep the delimiters when they are captured, i.e., enclosed in
parentheses:

    
    
    import re
    s = '+ {- 9 4} {+ 3 2}'
    p = filter(lambda x: x.strip() != '', re.split("([+{} -])", s)) 
    

will give you

    
    
    ['+', '{', '-', '9', '4', '}', '{', '+', '3', '2', '}']
    

which, IMO, is what you need to handle nested expressions

