将字符串转换为操作符

如何将字符串(如 "+")转换为运算符 + ?

129377 次浏览

Use a lookup table:

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


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

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

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)

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)

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

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

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