Search code examples
pythonevaluation

Turn string into operator


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


Solution

  • Use a lookup table:

    import operator
    ops = { "+": operator.add, "-": operator.sub } # etc.
    
    print(ops["+"](1,1)) # prints 2