Michael Michael - 1 month ago 10
Python Question

Convert a string equation to an integer answer

If I have a string

equation = "1+2+3+4"

How do I change it into an int and equate the answer? I was thinking something like this but it would give an error.

answer = (int)equation

The equation could contain


If you are prepared to accept the risks, namely that you may be letting hostile users run whatever they like on your machine, you could use eval():

>>> equation = "1+2+3+4"
>>> eval(equation)

If your code will only ever accept input that you control, then this is the quickest and simplest solution. If you need to allow general input from users other than you, then you'd need to look for a more restrictive expression evaluator.


Thanks to @roippi for pulling me up and pointing out that the code above executes in the environment of the calling code. So the expression would be evaluated with local and global variables available. Suppress that like so:

eval(equation, {'__builtins__': None})

This doesn't make the use of eval() secure. It just gives it a clean, empty environment in which to operate. A hostile user could still hose your system.