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:
_ as a new operator in the future, the code won't know to split according to it). # 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', ')']
Here is a way to go:
import re
arr = [
'5--5',
'((500-4)*-3)',
]
for s in arr:
res = re.findall(r'\b-\b|-?\d+|\D', s)
print res
Output:
['5', '-', '-5']
['(', '(', '500', '-', '4', ')', '*', '-3', ')']
Demo & explanation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With