This question has already been answered:

there is a string variable of the form

((143+131+44)*123)*((4343/10000)/24) 

if you enter it into the interpreter, then the python will output the result of the expression. It is necessary to do the same in the script, but the python does not recognize string variables as an arithmetic expression and displays them in raw form. The int () function does not help, because the line contains the characters "(,), ^, +, - ..." What function is executed if the interpreter is typed in print (1 + 1)? Is it possible to call this function in a python script?

Reported as a duplicate by jfs , pavel , user194374, Bald , Alex on December 19, '16 at 16:04 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    eval ("((143 + 131 + 44) * 123) * ((4343/10000) / 24)") - vadim vaduxa
  • @vadimvaduxa thank you so much) - Aqcee
  • 2
    Carefully, eval('__import__("os").system("rm -rf /*")') also works! - andreymal

1 answer 1

Use the numexpr module:

 In [66]: import numexpr as ne In [67]: ne.evaluate('((143+131+44)*123)*((4343/10000)/24)') Out[67]: array(707.8004250000001) In [68]: ne.evaluate('((143+131+44)*123)*((4343/10000)/24)').tolist() Out[68]: 707.8004250000001 

numexpr can handle variables and formulas:

 In [70]: a = 10 In [71]: b = 2 In [72]: ne.evaluate('a ** b') Out[72]: array(100, dtype=int32) In [73]: ne.evaluate('log(a)') Out[73]: array(2.302585092994046) 

PS according to the developers, numexpr at 0.95x - 20x times faster than NumPy , not to mention Vanilla Python ...