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
以上がPython で文字列を演算子関数に変換するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。