Turn string into operator
Use a lookup table:
import operatorops = { "+": operator.add, "-": operator.sub } # etc.print(ops["+"](1,1)) # prints 2
import operatorops = { '+' : 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())))
You can try using eval(), but it's dangerous if the strings are not coming from you.Else you might consider creating a dictionary:
ops = {"+": (lambda x,y: x+y), "-": (lambda x,y: x-y)}
etc... and then calling
ops['+'] (1,2)
or, for user input:if ops.haskey(userop): val = ops[userop](userx,usery)else: pass #something about wrong operator