I'm new to Python and I'm trying to create some kind of a calculator that reads expressions as strings and calculates them (without eval). In order to do so I'm working with a list after converting the string to a list separated by parentheses, operators and values. I have a list that contains the operators too, I just don't know how to use it in the regex split so up until now I've done that manually.
I have 3 issues with my code:
- The code doesn't split correctly negative numbers.
- The code doesn't allow to add operators (in example - if I'd like to add
_as a new operator in the future, the code won't know to split according to it). - The code brings back numbers as strings, which I then convert to integers in an outside function.
# Removing any unwanted white spaces, tabs, or new lines from the equation string:
equation = re.sub(r"[\n\t\s]*", "", equation)
# Creating a list based on the equation string:
result_list = re.split(r'([-+*/^~%!@$&()])|\s+', equation)
# Filtering the list - Removing all the unwanted "spaces" from the list:
result_list = [value for value in result_list if value not in ['', ' ', '\t']]
For example: 5--5 -> I'd like to get: [5, '-', -5] -> I currently get: ['5', '-', '-', '5']
Another example : ((500-4)*-3) -> I'd like to get: ['(', '(', 500, '-', '4', ')', *', '-3', ')']
+,-) by only splitting when they are preceded by a digit i.e. use a positive lookbehind(?<=\d)to qualify the split