字符串中的数学运算 [英] Math operations from string

查看:100
本文介绍了字符串中的数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个标准的Python字符串(例如从raw_input()获得的字符串),为简单起见,也许是"2 + 2".

Let's say I have a standard Python string (such as one obtained from raw_input()), maybe "2 + 2" for simplicity's sake.

我想将此字符串转换为Python中的标准数学运算,以使"2 + 2"返回4.

I'd like to convert this string to standard math operations in Python, such that "2 + 2" would return 4.

是否有一种简单的方法来执行此操作,还是我必须拆分空格并手动解析每个数字/符号,然后根据找到的内容进行数学运算?

Is there an easy way to do this, or would I have to split on the spaces and parse each number/symbol manually, then do the math based on what I find?

我想要正则表达式吗?

推荐答案

警告:这种方法不是安全的方法,但是非常易于使用.明智地使用它.

使用eval函数.

print eval('2 + 4')

输出:

6

您甚至可以使用变量或常规python代码.

You can even use variables or regular python code.

a = 5
print eval('a + 4')

输出:

9

您还可以获得返回值:

d = eval('4 + 5')
print d

输出:

9

或调用函数:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a = 20
b = 10    
print eval('add(a, b)')
print eval('subtract(a, b)')

输出:

30
10

如果您想编写一个解析器,也许更简单的是,您可以构建一个python代码生成器,并使用eval运行代码.使用eval可以执行任何Python评估.

In case you want to write a parser, maybe instead you can built a python code generator if that is easier and use eval to run the code. With eval you can execute any Python evalution.

为什么评估不安全?

因为您可以在评估中实际输入任何内容,例如如果输入参数为:

Since you can put literally anything in the eval, e.g. if the input argument is:

os.system(‘rm -rf /’)

它将删除系统上的所有文件(至少在Linux/Unix上). 因此,只有在您信任输入时才使用eval.

It will remove all files on your system (at least on Linux/Unix). So only use eval when you trust the input.

这篇关于字符串中的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆