In Python, can I evaluate a string (eg. “math.sin(3)+max(5,3)”) without using the dreaded eval(), and preferably with Decimal precision? Note: it is not a simple mathematical expression such as "3*2", which is easy. Also x = math.sin(3)+max(5,3) will give an answer, but x = "math.sin(3)+max(5,3)" will merely give you a string of characters, and float("math.sin(3)+max(5,3)") will give a ValueError, could not convert string to float:
Asked
Active
Viewed 906 times
2 Answers
1
since math.sin(3) and math.sin(3) both gives you float and integers respectively you don't need to use eval to evaluate them. moreover you can specify a userdefined function for evaluating expression
here I demonstrated such function for evaluating expressions with primary mathematical operations for smaller expression like "a + b"
def evaluate(expression):
expression = expression.replace(" ", "")
expression = [j for j in expression]
num1 = float(expression[0])
i = expression[1]
num2 = float(expression[2])
if i == "+":
return num1+num2
elif i == "-":
return num1-num2
elif i == "*":
return num1*num2
elif i == "/":
return num1/num2
else:
return "Error in Expression Format"
print(evaluate("5 + 4"))

Harshil Khamar
- 186
- 1
- 6
1
To evaluate more complex expressions, the python ast package is probably what you're looking for. But you still have to parse the calls to the 'math' package (or any other functions you would like to use in your expressions). An interesting answer is provided in this post

A.arnaud
- 21
- 2