I'm trying to insert a variable mathematical operator into a if statement, an example of what I'm trying to achieve in parsing user-supplied mathematical expressions:
maths_operator = "=="
if "test" maths_operator "test":
print "match found"
maths_operator = "!="
if "test" maths_operator "test":
print "match found"
else:
print "match not found"
obviously the above fails with SyntaxError: invalid syntax
. I've tried using exec and eval but neither work in an if statement, what options do I have to get around this?
For the sake of completeness it should be mentioned that they do work, even if the posted answers provide a better solution. You'll have to eval() the whole comparison, not just the operator:
or exec the line:
Use the
operator
module:Use the operator package together with a dictionary to look up the operators according to their text equivalents. All of these must be either unary or binary operators to work consistently.