Home >Backend Development >Python Tutorial >How to Convert Strings to Operators in Python?
Converting Strings to Operators in Python
It is possible to convert a string representing an operator, such as " " or "-", into the corresponding Python operator object. This can be achieved using a lookup table.
For instance, one can define a dictionary that maps strings representing operators to the corresponding operator functions:
import operator ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}
To use this lookup table, simply index it with the string representing the desired operator:
result = ops["+"](1, 1) # Returns 2
This approach provides a convenient way to dynamically select and apply operators based on input strings.
The above is the detailed content of How to Convert Strings to Operators in Python?. For more information, please follow other related articles on the PHP Chinese website!