Evaluating an expression as you mention is relatively simple, as NaCI has already mentioned, you can use eval
which is base functionality:
from math import sqrt
valor = eval("2*3")
print(valor)
> 6
valor = eval("sqrt(4)")
print(valor)
> 2.0
But eval()
does not evaluate arithmetic operations evaluates Python code, therefore it is a dangerous routine, if you are going to offer it to a user, you are opening the possibility of executing any code.
A more limited solution is to use some mathematical evaluator, there are several. Simply by way of example I can suggest py-expression-eval
The installation, in the usual way: pip install py_expression_eval
To execute it:
from py_expression_eval import Parser
parser = Parser()
valor = parser.parse('2 * 3').evaluate({})
print(valor)
Verify in PyPI , there are simpler evaluators and others more complex, the idea is always the same, offer a code evaluation more limited to the mathematical and minimize the problems due to the execution of undesired code.