tags:

views:

241

answers:

6

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

A: 

use eval.

eval("+")

Cheers, Raj

Raj
this causes syntax error
Xinus
+16  A: 

Use a lookup table:

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

print ops["+"](1,1) # prints 2
Amnon
Simple and clean. Thanks!
hwong557
+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-
+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
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
A: 

eval is just what I was looking for.. thank you!

K-man