12

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!")
4
  • You should parse the string and handle the different conditional options Commented May 9, 2017 at 19:42
  • 1
    Any particular reason you're not doing ifinner = x == 3, which works in your example? Commented May 9, 2017 at 19:42
  • 1
    In the real situation, where is the string coming from? Commented May 9, 2017 at 19:45
  • Possible duplicate of How do I execute a string containing Python code in Python? Commented Oct 14, 2017 at 13:41

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

1 Comment

but never use eval on any string that you didn't create yourself (or from a trusted source)!
3

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

Comments

2

I think eval does not work with strings like this

str_ = "import matplotlib"

in that case you might have to open a separate file, write the string and then execute it.

1 Comment

you can use exec for this string. For example try the following exec( "import matplotlib.pyplot as mp" ); mp.plot([1,2,3],[-1,0,1]); mp.show() no error. But you are right that eval is not suitable for this string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.