How to turn string into operator with Python?

Sometimes, we want to turn string into operator with Python.

In this article, we’ll look at how to turn string into operator with Python.

How to turn string into operator with Python?

To turn string into operator with Python, we can use the operator module.

For instance, we write

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

print(ops["+"](1,1))

to create the ops dict that has the operator strings as keys and the operators as the values.

Then we can get the operator by the string key and use them with operands.

Conclusion

To turn string into operator with Python, we can use the operator module.