Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert string to source code in python?

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!")
like image 582
Turcsi Avatar asked Mar 07 '26 02:03

Turcsi


2 Answers

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.

like image 170
Laurent LAPORTE Avatar answered Mar 08 '26 14:03

Laurent LAPORTE


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

like image 43
Bilal Ch Avatar answered Mar 08 '26 16:03

Bilal Ch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!