Reputation: 760
I read the conditions ">0", "<60", etc., from a xml file. What is the best way to convert them to python language to compare? The sample code is what I want to do:
if str == ">0":
if x > 0:
print "yes"
else:
print "no"
elif str == "<60":
if x < 60:
print "yes"
...
Upvotes: 2
Views: 172
Reputation: 6607
If you are very confident that the data in the XML file is properly sanitized, then you could use eval()
.
'yes' if eval(str(x) + op) else 'no'
Although this solution is much simpler than the other answers, it is also probably slower (however I have not tested this).
Upvotes: 1
Reputation: 22292
Maybe simply use slice?
string = "<60"
x = 3
op = string[0]
number = int(string[1:].strip())
if op == '>':
print 'yes' if x > number else 'no'
else:
print 'yes' if x < number else 'no'
Output:
yes
Upvotes: 0