I am looking for a function specifically for python 3.7. I have a mathematical expression in a string :
str="2^10" #Expected output: 1024
Is there any in-built function in python 3.7 to evaluate it?
P.S: eval() function doesnt work.
I am looking for a function specifically for python 3.7. I have a mathematical expression in a string :
str="2^10" #Expected output: 1024
Is there any in-built function in python 3.7 to evaluate it?
P.S: eval() function doesnt work.
The symbol for power operations in Python is **
, not ^
. So, change your string first.
str_ ="2^10"
print(eval(str_.replace('^', '**'))) # -> 1024
Note that eval
is a potentially very dangerous function. Do not use it blindly.
A safer way would be with the (non-standard) module numexpr
.
import numexpr
print(numexpr.evaluate(str_.replace('^', '**'))) # -> 1024
Also note that not replacing "^"
with "**"
would result in 8
. That happens because in Python ^
is the binary XOR