-2

Say I have this string. "+2x-10+5". I want to split it into ['+2x','-10','+5'].

So, I can use regular expression to make it ['2x','10','5'], but I want to keep the separators, which are the plus and minus signs.

How do I do this?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • If you could share your code which you have come up with so far, then it would be much easier to help you out :) – S.D. Jul 17 '20 at 15:59
  • There could be a few different approaches to this. Can you show what you have written so far. You could either, instead of using split, just use a regex to capture in groups like `([+-]?\w+)` with re.findall. Alternatively if you really want to use re.split you could use a positive look ahead and look behind for the split. for example ` (?<=\w)(?=[+-])` – Chris Doyle Jul 17 '20 at 15:59

1 Answers1

0

Don't use re.split(), use re.findall() with a regexp that matches each sub-expression.

import re

s = "+2x-10+5"
result = re.findall(r'[-+]\w+', s)
print(result)
Barmar
  • 741,623
  • 53
  • 500
  • 612