Luke
Luke

Reputation: 760

Convert string ">0" to python > 0

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

Answers (3)

pzp
pzp

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

Remi Guan
Remi Guan

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

Delgan
Delgan

Reputation: 19677

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.

Upvotes: 8

Related Questions