0

I have a program where i have an input and want to calculate it (eg input = "3+2**5) and I would like to know if there`s any package to calculate it easily.

x = "5*70 y = x.calculate() print(y)" just a simple example

Fredkit
  • 1
  • 1
  • 1
    Is `x.calculate() print(y)` really supposed to be in the string? – Barmar Feb 21 '23 at 21:46
  • 1
    You can use the built-in `eval()` function. – Barmar Feb 21 '23 at 21:46
  • 1
    I would recommend [ast.literal_eval()](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) instead. – Michael Cao Feb 21 '23 at 21:56
  • 1
    Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string). And if you look at the comments on the accepted answer to that question, you'll find this package: https://github.com/danthedeckie/simpleeval which was adapted from the answer! – Stef Feb 21 '23 at 22:23
  • @MichaelCao `ast.literal_eval` doesn't work for expressions, only literals – Mous Feb 21 '23 at 22:36

1 Answers1

0

Just try function eval() For example:

x = "5*70"
print(eval(x))

350

kot.shubin
  • 26
  • 2