How can I turn a string such as "+" into the operator plus? Thanks!
this causes syntax error
Xinus
2009-11-16 08:05:45
+16
A:
Use a lookup table:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print ops["+"](1,1) # prints 2
Amnon
2009-11-16 08:09:15
+1
A:
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
raceCh-
2009-11-16 08:09:16
+6
A:
import operator
def get_operator_fn(op):
return {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.div,
'%' : operator.mod,
'^' : operator.xor,
}[op]
def eval_binary_expr(op1, operator, op2):
op1,op2 = int(op1), int(op2)
return get_operator_fn(operator)(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()))
Paul McGuire
2009-11-16 08:09:34
A:
In my opinion, the answer proposed by Amnon is the right one.
However, you may also be interested by this article about a mathematical parser: http://effbot.org/zone/simple-top-down-parsing.htm
luc
2009-11-16 08:27:35