Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating strings as values

Tags:

python

string

Is it possible in Python to calculate a term in a string? For example:

string_a = "4 ** (3 - 2)"

unknown_function(string_a) = 4

Is this possible? Is there a function that mimics "unknown_function" in my example?

like image 561
Paul Terwilliger Avatar asked Nov 28 '22 17:11

Paul Terwilliger


2 Answers

There is eval

eval(string_a)
# 4

But do not use this under any circumstances if string_a comes from anyone but you, because they can easily hack into your system and destroy your files!

like image 80
Volatility Avatar answered Dec 21 '22 23:12

Volatility


Just like sympy was a useful module for your last question, it can apply here:

>>> import sympy
>>> sympy.sympify("4**(3-2)")
4

and even

>>> sympy.sympify("2*x+y")
2*x + y
>>> sympy.sympify("2*x+y").subs(dict(x=2, y=3))
7

Note though that this will return sympy objects, and if you want to get an integer or a float out of it you should do the conversion explicitly:

>>> type(sympy.sympify("4**(3-2)"))
<class 'sympy.core.numbers.Integer'>
>>> int(sympy.sympify("4**(3-2)"))
4

I hacked together a recipe to turn string expressions into functions here which is kind of cute.

like image 39
DSM Avatar answered Dec 22 '22 00:12

DSM