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"
...
I would use regex and operator.
from operator import lt, gt
import re
operators = {
">": gt,
"<": lt,
}
string = ">60"
x = 3
op, n = re.findall(r'([><])(\d+)', string)[0]
print(operators[op](x, int(n)))
Depending on your string, the regex can be modified.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With