bjskistad bjskistad - 3 months ago 24
Python Question

Parsing string as boolean?

Is it possible to parse a string in a

if
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

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 /') :/

Comments