Python 计算字符串中的算术运算

Python 计算字符串中的算术运算

算术运算是对数字数据类型进行数学计算的操作。以下是Python中允许的算术运算。

  • 加法(+

  • 减法(-

  • 乘法(*

  • 除法(/

  • 地板除法(//

  • 取模(%

  • 指数运算(**

有几种方法可以从字符串中计算算术运算。让我们逐个看看。

使用eval()函数

在Python中,eval()函数评估作为字符串传递的表达式并返回结果。我们可以使用这个函数来计算字符串中的算术运算。

示例

在这种方法中,eval()函数评估表达式”2 + 3 * 4 – 6 / 2″并返回结果,然后将结果存储在变量”result”中。

def compute_operation(expression):
   result = eval(expression)
   return result
expression = "2 + 3 * 4 - 6 / 2"
result = compute_operation(expression)
print("The result of the given expression:",result)

输出

The result of the given expression: 11.0

实施算术解析和计算

如果我们想对解析和计算过程有更多的控制,我们可以实现自己的算术解析和计算逻辑。这种方法涉及将字符串表达式拆分为单个操作数和操作符,解析它们,并根据算术操作进行运算。

示例

在这个例子中,使用split()方法将表达式拆分为单个标记。然后,根据operators字典中指定的算术运算符,迭代地解析和计算这些标记。通过将累积结果和当前操作数应用于相应的运算符来计算结果。

def compute_operation(expression):
   operators = {'+': lambda x, y: x + y,
                  '-': lambda x, y: x - y,
                  '*': lambda x, y: x * y,
                  '/': lambda x, y: x / y}
   tokens = expression.split()
   result = float(tokens[0])
   for i in range(1, len(tokens), 2):
      operator = tokens[i]
      operand = float(tokens[i+1])
      result = operators[operator](result, operand)
   return result
expression = "2 + 3 * 4 - 6 / 2"
result = compute_operation(expression)
print("The result of given expression",result)

输出

The result of given expression 7.0

使用operator模块

在python中,我们有operator模块,它提供了对应于内置Python运算符的函数。我们可以使用这些函数根据字符串表达式中的运算符执行算术运算。

示例

在这个示例中,我们定义了一个将运算符映射到operator模块中相应函数的字典。我们将表达式分割成标记,其中运算符和操作数分开。然后,我们遍历这些标记,将相应的运算符函数应用于结果和下一个操作数。

import operator
expression = "2 + 3 * 4"
ops = {
   '+': operator.add,
   '-': operator.sub,
   '*': operator.mul,
   '/': operator.truediv,
}
tokens = expression.split()
result = int(tokens[0])
for i in range(1, len(tokens), 2):
   operator_func = ops[tokens[i]]
   operand = int(tokens[i + 1])
   result = operator_func(result, operand)
print("The arithmetic operation of the given expression:",result)

输出

The arithmetic operation of the given expression: 20

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程