Turn string into operator
import operator
ops = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv, # use operator.div for Python 2
'%' : operator.mod,
'^' : operator.xor,
}
def eval_binary_expr(op1, oper, op2):
op1, op2 = int(op1), int(op2)
return ops[oper](op1, op2)
print(eval_binary_expr(*("1 + 3".split())))
print(eval_binary_expr(*("1 * 3".split())))
print(eval_binary_expr(*("1 % 3".split())))
print(eval_binary_expr(*("1 ^ 3".split())))
Use a lookup table:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print(ops["+"](1,1)) # prints 2