简体   繁体   English

python解决字符串内的方程式

[英]python solve equation inside string

I have this code 我有这个代码

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

Which prints this as answer 这打印出来作为答案

105

This is not correct, the idea is to get the ecuation from a web page (I already have that part working) and solve it. 这是不正确的,我的想法是从网页获取信息(我已经有了这部分工作)并解决它。

note: The ecuation will always change but it will always be adding and substracting numbers. 注意:通知将始终改变,但它将始终是添加和减少数字。

You can try using the eval function: 您可以尝试使用eval函数:

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

However, you need to be very careful while using this. 但是,使用它时需要非常小心 A safer way is: 更安全的方法是:

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

Try 尝试

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

Using re : 使用re

import re

ecuation= "95502+45806-85773-659740"

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

Prints: 打印:

-604205

What you're doing is this calculation: 你正在做的是这个计算:

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

What you want to do is break apart the string and add/subtract those numbers. 你想要做的是拆开字符串并添加/减去这些数字。 This can be shortcut by using eval() (more here ), as suggested by Vitor, or with ast.literal_eval (more here ), as suggested by rassar. 这可以是使用eval()(更多这里 )的快捷方式,如Vitor所建议的,或者使用ast.literal_eval( 此处更多),如rassar所建议的那样。

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

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