How to Convert Strings to Operators in Python?

DDD
Release: 2024-11-13 00:05:02
Original
299 people have browsed it

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

To use this lookup table, simply index it with the string representing the desired operator:

result = ops["+"](1, 1)  # Returns 2
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template