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?
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With