Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string ">0" to python > 0

Tags:

python

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"
    ...
like image 349
Luke Avatar asked Sep 19 '26 13:09

Luke


2 Answers

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.

like image 57
Delgan Avatar answered Sep 22 '26 05:09

Delgan


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).

like image 20
pzp Avatar answered Sep 22 '26 05:09

pzp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!