Home >Backend Development >Python Tutorial >How to Convert Strings to Operator Functions in Python?
Finding Operators from Strings
In Python, it is possible to convert a string representing an operator, such as " ", into the corresponding operator function.
Solution: Utilize a Lookup Table
One effective approach is to leverage a lookup table. Create a dictionary ops, where the keys are strings representing operators, and the values are the corresponding operator functions from operator module. For instance:
import operator ops = { "+": operator.add, "-": operator.sub }
Now, you can retrieve the operator function by accessing the dictionary with the operator's string representation. For example, to obtain the addition operator:
add_operator = ops["+"]
Usage
Once you have the desired operator, you can use it like any other function:
result = add_operator(num1, num2)
Example
Consider evaluating the expression "1 1" using this approach:
first_num = 1 second_num = 1 add_operator = ops["+"] result = add_operator(first_num, second_num) print(result) # Prints 2
The above is the detailed content of How to Convert Strings to Operator Functions in Python?. For more information, please follow other related articles on the PHP Chinese website!