-2

I'm looking fo an elegenat way to split a string by multiple delimiters and keep the delimiters at which the string got splitted.

Example:

input_str = 'X < -500 & Y > 3000 / Z > 50'
split_str = re.split("and | or | & | /", input_str)
print split_str
>>> ['X < -500', ' Y > 3000',  'Z > 50']

What I want so get for split_str would be:

['X < -500', '&', ' Y > 3000', '/', 'Z > 50']

1 Answers1

1

Try with parenthesis:

>>> split_str = re.split("(and | or | & | /)", input_str)
>>> split_str
['X < -500', ' & ', 'Y > 3000', ' /', ' Z > 50']
>>> 

If you want to remove extra spaces:

>>> split_str = [i.strip() for i in re.split("(and | or | & | /)", input_str)]
>>> split_str
['X < -500', '&', 'Y > 3000', '/', ' Z > 50']
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114