How do I divide into math operators separated by spaces?

I have a custom calculator that accepts both numbers and user-defined variables. My plan is to split the operator into a space delimited operator, for example. '+':

import re
query = 'house-width + 3 - y ^ (5 * house length)'
query = re.findall('[+-/*//]|\d+|\D+', query)
print query  # ['house-width + ', '3', ' - y ^ (', '5', ' * house length)']

Expecting:
['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']

      

0


source to share


1 answer


Using re.split

with capturing parentheses around the split pattern seems to work quite efficiently. As long as you have the capture patterns in the template, the templates you split are stored in the resulting list:

re.split(' ([+-/*^]|//) ', query)
Out[6]: ['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']

      



(PS: I am assuming from your original regex you want to catch //

integer division operators , you cannot do that with a single character class, so I moved it outside the character class as a special case.)

+4


source







All Articles