Home > Backend Development > Python Tutorial > How to Convert Strings to Operator Functions in Python?

How to Convert Strings to Operator Functions in Python?

Linda Hamilton
Release: 2024-11-15 09:57:03
Original
481 people have browsed it

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 }
Copy after login

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["+"]
Copy after login

Usage

Once you have the desired operator, you can use it like any other function:

result = add_operator(num1, num2)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template