Turn string into operator

Solution 1:

Use a lookup table:

import operator
ops = { "+": operator.add, "-": operator.sub } # etc.

print(ops["+"](1,1)) # prints 2 

Solution 2:

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

Solution 3:

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

Solution 4:

How about using a lookup dict, but with lambdas instead of operator library.

op = {'+': lambda x, y: x + y,
      '-': lambda x, y: x - y}

Then you can do:

print(op['+'](1,2))

And it will output:

3