繁体   English   中英

python解决字符串内的方程式

[英]python solve equation inside string

我有这个代码

ecuation=("95502+45806-85773-659740")
answer = sum(int(x) for x in ecuation if x.isdigit())
print(answer)

这打印出来作为答案

105

这是不正确的,我的想法是从网页获取信息(我已经有了这部分工作)并解决它。

注意:通知将始终改变,但它将始终是添加和减少数字。

您可以尝试使用eval函数:

>>> ecuation=("95502+45806-85773-659740")
>>> eval(ecuation)
-604205

但是,使用它时需要非常小心 更安全的方法是:

>>> import ast
>>> ast.literal_eval(ecuation)
-604205

尝试

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

使用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

你想要做的是拆开字符串并添加/减去这些数字。 这可以是使用eval()(更多这里 )的快捷方式,如Vitor所建议的,或者使用ast.literal_eval( 此处更多),如rassar所建议的那样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM