Categories
Python Answers

How to turn string into operator with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *