Paul Terwilliger Paul Terwilliger - 23 days ago 5
Python Question

Calculating strings as values

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?

Answer

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!