Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python在字符串中求解方程_Python_Python 2.7 - Fatal编程技术网

python在字符串中求解方程

python在字符串中求解方程,python,python-2.7,Python,Python 2.7,我有这个密码 ecuation=("95502+45806-85773-659740") answer = sum(int(x) for x in ecuation if x.isdigit()) print(answer) 打印这个作为答案 105 这是不正确的,我们的想法是从一个网页(我已经有了工作的一部分)获得的ecuation,并解决它 注意:运算将始终更改,但它将始终添加和删除数字。请尝试 ecuation=("95502+45806-85773-659740") answer =

我有这个密码

ecuation=("95502+45806-85773-659740")
answer = sum(int(x) for x in ecuation if x.isdigit())
print(answer)
打印这个作为答案

105
这是不正确的,我们的想法是从一个网页(我已经有了工作的一部分)获得的ecuation,并解决它

注意:运算将始终更改,但它将始终添加和删除数字。

请尝试

ecuation=("95502+45806-85773-659740")
answer = eval(ecuation)
print(answer)

您可以尝试使用
eval
功能:

>>> ecuation=("95502+45806-85773-659740")
>>> eval(ecuation)
-604205
但是,在使用此工具时,您需要保持谨慎。一种方法是:

使用
re

import re

ecuation= "95502+45806-85773-659740"

s = sum(int(g) for g in re.findall(r'((?:\+|-)?\d+)', ecuation))
print(s)
印刷品:

-604205

你所做的是这样的计算:

9+5+5+0+2+4+5+8+0+6+8+5+7+7+3+6+5+9+7+4+0=105

你要做的是把字符串分开,然后加/减这些数字。Vitor建议使用eval()(更多),或者rassar建议使用ast.literal_eval(更多),这可能是一种快捷方式。

关于
eval()
请注意,如果方程式来自用户输入,这可能是一个安全问题,因为有害代码可能会以这种方式运行……建议使用literal_evalliteral_eval只对添加项有效。不是用乘法或除法。但这是个好把戏。不确定这是否重要,但这对小数不起作用。
9+5+5+0+2+4+5+8+0+6+8+5+7+7+3+6+5+9+7+4+0=105