Turn string into operator

PythonEvaluation

Python Problem Overview


How can I turn a string such as "+" into the operator plus?

Python Solutions


Solution 1 - Python

Use a lookup table:

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

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

Solution 2 - Python

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 - Python

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 = opsuserop
else:
pass #something about wrong operator

Solution 4 - Python

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

Solution 5 - Python

There is a magic method corresponding to every operator

OPERATORS = {'+': 'add', '-': 'sub', '*': 'mul', '/': 'div'}

def apply_operator(a, op, b):
    
    method = '__%s__' % OPERATORS[op]
    return getattr(b, method)(a)

apply_operator(1, '+', 2)

Solution 6 - Python

Use eval() if it is safe (not on servers, etc):

num_1 = 5

num_2 = 10

op = ['+', '-', '*']

result = eval(f'{num_1} {op[0]} {num_2}')

print(result)

Output : 15

Solution 7 - Python

I understand that you want to do something like: 5"+"7 where all 3 things would be passed by variables, so example:

import operator

#define operators you wanna use
allowed_operators={
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv}

#sample variables
a=5
b=7
string_operator="+"

#sample calculation => a+b
result=allowed_operators[string_operator](a,b)
print(result)

Solution 8 - Python

I was bugged with the same problem, using Jupyter Notebook, I was unable to import the operator module. So the above code helped give me insight but was unable to run on the platform. I figured out a somehwhat primitive way to do so with all the basic funcs and here it is: (This could be heavily refined but it’s a start…)

# Define Calculator and fill with input variables
# This example "will not" run if aplha character is use for num1/num2 
def calculate_me():
    num1 = input("1st number: ")
    oper = input("* OR / OR + OR - : ")
    num2 = input("2nd number: ")
    
    add2 = int(num1) + int(num2)
    mult2 = int(num1) * int(num2)
    divd2 = int(num1) / int(num2)
    sub2 = int(num1) - int(num2)

# Comparare operator strings 
# If input is correct, evaluate operand variables based on operator
    if num1.isdigit() and num2.isdigit():
        if oper is not "*" or "/" or "+" or "-":
            print("No strings or ints for the operator")
        else:
            pass
        if oper is "*":
            print(mult2)
        elif oper is "/":
            print(divd2)
        elif oper is "+":
            print(add2)
        elif oper is "-":
            print(sub2)
        else:
            return print("Try again")

# Call the function
calculate_me()
print()
calculate_me()
print()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhwong557View Question on Stackoverflow
Solution 1 - PythonAmnonView Answer on Stackoverflow
Solution 2 - PythonPaulMcGView Answer on Stackoverflow
Solution 3 - PythonKrzysztof BujniewiczView Answer on Stackoverflow
Solution 4 - PythonGarrettView Answer on Stackoverflow
Solution 5 - PythonVinayak KaniyarakkalView Answer on Stackoverflow
Solution 6 - PythonKameliaView Answer on Stackoverflow
Solution 7 - PythonPawel SzewczykView Answer on Stackoverflow
Solution 8 - PythonKamron HopkinsView Answer on Stackoverflow