0

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
5
  • 1
    Sure, that's what the builtin eval does ... But doing this can lead to security issues. Commented Oct 17, 2012 at 16:52
  • Don't eval it. Commented Oct 17, 2012 at 16:52
  • 1
    possible duplicate of Evaluating a mathematical expression in a string Commented Oct 17, 2012 at 17:01
  • what about literaleval, its a bit safer. Commented Oct 17, 2012 at 17:03
  • @InbarRose literal_eval() doesn't works for mathematical expressions. Commented Oct 17, 2012 at 17:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

eval(operation.replace('__',''),{'__builtins__':None,'math':math}) may be a bit safer ...

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.