4

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!")
Erik A
  • 30,261
  • 11
  • 41
  • 58
Turcsi
  • 75
  • 1
  • 2
  • 4
  • You should parse the string and handle the different conditional options – b-fg May 09 '17 at 19:42
  • 1
    Any particular reason you're not doing `ifinner = x == 3`, which works in your example? – Kevin May 09 '17 at 19:42
  • 1
    In the real situation, where is the string coming from? – jonrsharpe May 09 '17 at 19:45
  • Possible duplicate of [How do I execute a string containing Python code in Python?](https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python) – jpyams Oct 14 '17 at 13:41

3 Answers3

12

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.

Laurent LAPORTE
  • 20,141
  • 5
  • 53
  • 92
1

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

Community
  • 1
  • 1
Bilal Ch
  • 310
  • 3
  • 13
0

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.

Henry Ecker
  • 31,792
  • 14
  • 29
  • 50
peter
  • 84
  • 8