I’ve seen similar questions but none of them seem to help for what I’m trying to do and have spent ages trying to work thru the RE documentation with no luck so far.
I am currently splitting a string
my str = 'a+0b-2a+b-b'
re.split(r'([+-])', my_str)
which gives me the strings and the separators in a list
['a', '+', '0b', '-', '2a', '+', 'b', '-', 'b']
But I’d like the separators, which are + or – to be included in the next string, not as a separate item. So the result should be:
['a', '+0b', '-2a', '+b', '-b']
Appreciate any help
If you are using python 3.7+ you can split by zero-length matches using re.split
and positive lookahead:
string = 'a+0b-2a+b-b'
re.split(r'(?=[+-])', string)
# ['a', '+0b', '-2a', '+b', '-b']
Demo: https://regex101.com/r/AB6UBa/1
1
Try with re.findall
:
my_str = 'a+0b-2a+b-b'
re.findall(r'([+-]?[^+-]*)', my_str)
Outputs:
['a', '+0b', '-2a', '+b', '-b', '']