bjskistad bjskistad - 1 year ago 119
Python Question

Parsing string as boolean?

Is it possible to parse a string in a

statement as a string? Something like

if "1 > 2":
print "1 is greater than 2"

But is parsed as

if 1 > 2:
print "1 is greater than 2"

Is this possible? Is the a program out there that does this?

Answer Source

That's what eval is for.

if eval("1 > 2"):
    print "1 is greater than 2"

Be careful with eval, though. It will call any function supplied to it. Like os.system('rm -rf /') :/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download