search
HomeBackend DevelopmentPython TutorialPython program for calculating arithmetic operations from strings
Python program for calculating arithmetic operations from stringsAug 19, 2023 pm 01:21 PM
python programCompute arithmetic operationsString calculation

Python program for calculating arithmetic operations from strings

Arithmetic operations are mathematical calculations performed on numeric data types. The following are the arithmetic operations allowed by Python.

  • Addition ( )

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Floor Division (//)

  • Modulo (%)

  • Exponential operation (**)

There are several ways to perform arithmetic operations from strings. Let’s look at them one by one.

Use eval() function

In Python, the eval() function evaluates an expression passed as a string and returns the result. We can use this function to calculate arithmetic operations in strings.

The Chinese translation of

Example

is:

Example

In this method, eval() The function evaluates the expression "2 3 * 4 - 6 / 2" and returns the result, which is then stored in the variable "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)

Output

The result of the given expression: 11.0

Implementing arithmetic parsing and evaluation

If we wish to have more control over the parsing and evaluation process, we can implement our own arithmetic parsing and evaluation logic. This approach involves splitting a string expression into individual operands and operators, parsing them, and performing arithmetic operations accordingly.

The Chinese translation of

Example

is:

Example

In this example, the expression is split into individual tokens using the split() method. These tokens are then parsed and evaluated one by one based on the arithmetic operators specified in the operator dictionary. The result is calculated by applying the appropriate operator to the accumulated result and the current operand.

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)

Output

The result of given expression 7.0

Use operator module

In Python, we have the operator module, which provides functions corresponding to the built-in Python operators. We can use these functions to perform arithmetic operations based on operators in string expressions.

The Chinese translation of

Example

is:

Example

In this example, we define a dictionary that maps operators to their corresponding functions in the operator module. We split the expression into tokens where operators and operands are separated. We then iterate over these tokens, applying the corresponding operator function to the result and next operand.

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)

Output

The arithmetic operation of the given expression: 20

The above is the detailed content of Python program for calculating arithmetic operations from strings. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
PyCharm社区版支持的插件足够吗?PyCharm社区版支持的插件足够吗?Feb 20, 2024 pm 04:42 PM

PyCharm社区版支持的插件足够吗?需要具体代码示例随着Python语言在软件开发领域的应用越来越广泛,PyCharm作为一款专业的Python集成开发环境(IDE),备受开发者青睐。PyCharm分为专业版和社区版两个版本,其中社区版是免费提供的,但其插件支持相对专业版有所限制。那么问题来了,PyCharm社区版支持的插件足够吗?本文将通过具体的代码示例

PyCharm高级教程:利用PyInstaller将代码打包为EXE格式PyCharm高级教程:利用PyInstaller将代码打包为EXE格式Feb 20, 2024 am 09:34 AM

PyCharm是一款功能强大的Python集成开发环境,提供了丰富的功能和工具来帮助开发者提高效率。其中,PyInstaller是一个常用的工具,可以将Python代码打包为可执行文件(EXE格式),方便在没有Python环境的机器上运行。在本篇文章中,我们将介绍如何在PyCharm中使用PyInstaller将Python代码打包为EXE格式,并提供具体的

Python元编程:赋予你编程超能力的工具Python元编程:赋予你编程超能力的工具Feb 19, 2024 pm 04:45 PM

python元编程是一种强大的技术,它允许你对Python语言本身进行操作,赋予你编程超能力。元编程可以通过使用元类和装饰器来实现。元类是一种特殊的类,它负责创建其他类。装饰器是一种函数,它可以修改另一个函数的行为。元编程的一个常见用途是创建自定义的类。例如,你可以创建一个元类,它可以生成具有特定属性和方法的类。元编程还可以用于修改类的方法行为。例如,你可以创建一个装饰器,它可以对函数的输入和输出进行验证。元编程是一项强大的技术,它可以让你做很多有趣和有用的事情。如果你想成为一名更强大的Pyth

Python程序:从字符串的右侧修剪字符串Python程序:从字符串的右侧修剪字符串Sep 08, 2023 pm 06:21 PM

在Python中,我们有一个预定义的函数rstrip()来删除右侧的字符。这意味着它将删除字符串右侧的空格。让我们举一个例子来理解如何从字符串的左侧修剪。在给定的字符串“WIRELESS”中移除右侧字符串LESS并将结果值得到为“WIRE”。在给定的字符串“kingdom”中,删除右侧的字符串dom,得到结果值为“king”。语法以下示例中使用的语法为−isspace()这是Python中预定义的方法,用于允许字符中的空白、换行符或空格。rstrip("parameterasastri

Geany你是最后知道的!Geany你是最后知道的!Feb 03, 2024 pm 09:24 PM

我们来了解一下吧:Geany是一个小巧的使用GTK+2开发的跨平台的开源集成开发环境,以GPL许可证分发源代码,是免费的自由软件。当前版本:1.31。该软件小巧、启动迅速,界面简洁,功能简单。它支持基本的语法高亮、代码自动完成、调用提示、插件扩展。支持文件类型:C,CPP,Java,Python,PHP,HTML,DocBook,Perl,LateX和Bash脚本。对于写多种语言的程序员来说,拥有Geany可以说是非常的方便了。知道了这么多,是不是迫不及待想要去尝试一下呢?下面让我们开始进行下载

Python程序以删除字典中的空值为例Python程序以删除字典中的空值为例Sep 03, 2023 pm 04:45 PM

字典被称为集合数据类型。它们以键值对的形式存储数据。它们是有序的且可变的,即它们遵循特定的顺序并被索引。我们可以更改键的值,因此它是可操纵的或可更改的。字典不支持数据重复。每个键可以有多个与其关联的值,但单个值不能有多个键。我们可以使用字典来执行许多操作。整个机制取决于存储的值。在本文中,我们将讨论可用于从字典中删除“空值”的技术。在开始主要操作之前,我们必须对字典中的值处理有一个深入的了解。让我们快速浏览一下本文的概述。本文分为两部分-第1st部分将重点介绍“空值”的概念及其意义。在第2nd部

使用海龟绘制柱状图的Python程序使用海龟绘制柱状图的Python程序Aug 20, 2023 pm 04:57 PM

数据的图形表示提供了对数据复杂子结构的增强理解,帮助我们轻松解释隐藏的模式和趋势。想象一下,如果我们可以通过编程绘制类似的关系,那将是多么方便?Python提供了一个丰富的模块,专门用于执行此类操作,它被称为“turtle”。“turtle”模块是Python内置的库,允许我们在“turtle图形屏幕”上绘制图形。在本文中,我们将使用这个turtle模块创建一个条形图。理解Turtle模块Theturtlemoduleusesavirtualturtleobjecttocreategraphic

Python程序提取网格匹配字符串Python程序提取网格匹配字符串Sep 09, 2023 pm 10:21 PM

模式识别是一个重要的编程概念。它允许我们检索满足特定条件或匹配特定序列的特定数据。这一原理在语言和图像处理等各个领域都有帮助。字符串匹配帮助我们从大量数据中提取有意义的信息。在本文中,我们将讨论从给定字符串列表中提取网格匹配字符串的类似概念。网格匹配的重点是提取等长的“相似”字符串,我们来详细讨论这个问题。理解问题主要概念是提取遵循特定模式的相似字符串。网格字符串包含丢失的字符,并且应该提取与网格的隐藏模式匹配的那些字符串。让我们通过一个例子来理解这一点-输入输出场景Input:lis1=[&q

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!