如何将字符串解释为 Python 中的代码

How to interpret a string as code in Python

如何制作可以将字符串解释为代码的函数?

var1 = 5
var2 = 10
var3 = 7

str = "(var1*var2)+var3"


result = calculate(str) # I need help to write this function

结果应该输出 57

使用 result = eval(str) 而不是 result = calculate(str)

免责声明:应谨慎使用 eval(),因为它可以执行传递给它的任何内容。可以在 article.

中找到更多详细信息