python - How do I split on the space-separated math operators here? -
i have user calculator accepts both numbers , user-defined variables. plan split statement on space-delimited operator, e.g. ' + ':
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)']
using re.split
capturing parentheses around split pattern seems work effectively. long have capturing parens in pattern patterns splitting on kept in resulting list:
re.split(' ([+-/*^]|//) ', query) out[6]: ['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']
(ps: i'm assuming original regex want catch //
integer division operators, can't single character class, i've moved outside character class special case.)
Comments
Post a Comment