How can I convert string to source code in python?

随声附和 提交于 2020-01-30 08:25:26

问题


As you see, ifinner is a string, so if I just write after if, always will be true. What can i do, to concert it to source code?

    x=2
    ifinner = "x==3"
    if ifinner:
        print("Yeah")
    else:
        print("It works!")

回答1:


You can use eval() function to evaluate Python source code.

Quoting the documentation:

eval(expression, globals=None, locals=None)

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.




回答2:


Try this:

exec ("%s == 3" % x)

For detailed info, read the documentation of eval and exec in python 2.x/3.x. A similar question was asked previously.Here's the link



来源:https://stackoverflow.com/questions/43878504/how-can-i-convert-string-to-source-code-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!