简体   繁体   中英

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:

>>> 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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