Turn string into operator

hwong557 picture hwong557 · Nov 16, 2009 · Viewed 78.4k times · Source

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

Answer

Amnon picture Amnon · Nov 16, 2009

Use a lookup table:

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

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