0

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.

Anudocs
  • 686
  • 1
  • 13
  • 54
  • 1
    I am pretty sure it works https://repl.it/repls/WideeyedDutifulRecursion. However you might be looking for `str="2**10"` – DobromirM Apr 11 '19 at 11:19

1 Answers1

2

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

Ma0
  • 15,057
  • 4
  • 35
  • 65