Is it possible to convert string to a calculable operation
I want to make this done:
>>> import math
>>> operation = "10/2*6 + math.sqrt(42)"
>>> compute(operation)
36.48074069840786
tshepang
12.5k25 gold badges98 silver badges140 bronze badges
asked Oct 17, 2012 at 16:49
Arnaud Aliès
1,08914 silver badges27 bronze badges
1 Answer 1
eval will do that for you.
>>> import math
>>> operation = "10/2*6 + math.sqrt(42)"
>>> eval(operation)
36.48074069840786
answered Oct 17, 2012 at 16:52
Keith Randall
23.3k3 gold badges38 silver badges54 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
mgilson
eval(operation.replace('__',''),{'__builtins__':None,'math':math}) may be a bit safer ...lang-py
evaldoes ... But doing this can lead to security issues.evalit.literaleval, its a bit safer.literal_eval()doesn't works for mathematical expressions.