Reputation: 540
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
Thanks!
Upvotes: 2
Views: 2224
Reputation: 98118
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
Upvotes: 4