1

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

fazistinho_
  • 195
  • 1
  • 11

2 Answers2

3

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

hurlenko
  • 1,363
  • 2
  • 12
  • 17
  • I have a list of words *myList = ['to', 'for', 'go']* and I want to separate it by my string *(str)* on that list while including delimiter in the next section. How would I do that – Shaida Muhammad Jan 28 '22 at 10:34
1

Try with re.findall:

my_str = 'a+0b-2a+b-b'
re.findall(r'([+-]?[^+-]*)', my_str)

Outputs:

['a', '+0b', '-2a', '+b', '-b', '']
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34