Python - Evaluate math expression within string
Solution 1
Sometimes it's better to simplify the question rather than coming up with complicated solutions. You may want to simplify the problem by having your code be provided like this
my_str='I have {6 * (2 + 3)} apples'
This way you can parse it using a simple regex and eval what's inside. Otherwise you're in for a lot of complexity.
Solution 2
Here's my attempt:
>>> import string
>>> s = 'I have 6 * (2+3) apples'
>>> symbols = '^*()/+-'
>>> formula = [(x,s.index(x)) for x in s if x in string.digits+symbols]
>>> result = eval(''.join(x[0] for x in formula), {'__builtins__':None})
>>> s = s[:formula[0][1]] + str(result) + s[formula[-1][1]+1:]
>>> s
'I have 30 apples'
Notes:
This is very simple, it won't deal with complex equations - like those with square root, pi, etc. but I believe its in the spirit of what the question is after. For a really robust answer see the question posted by jeffery_the_wind; but I believe it may be overkill for this simplistic case.
Solution 3
This is a very tricky problem which is probably nearly impossible to solve in general. However, here's a simple way to attack the problem which works with the example input.
*step 1 -- sanitize the input. This is the hardest part to do in general. Basically, you need a way to pull a single math expression out of the string without mangling it. Here a simple regex will work:
sanitized = re.sub(r'[a-zA-Z]','',my_str).strip()
*step 2 -- evaluate using eval
:
value = eval(sanitized, {'__builtins__':None})
*step 3 -- back substitute
new_string = my_str.replace(sanitized, str(value))
Solution 4
Thanks to all for your help. Actually my provided example is very simple compared what I have in real task. I read these string from file and sometimes is can have view like this:
my_str='ENC M6_finger_VNCAPa (AA SYZE BY (0.14*2)) < (0.12 + 0.07) OPPOSITE REGION'
Math equation are simple but can occurs many time in one string, and should be evaluated separately.
So I write a sample code, which is able to handle this cases: Maybe it is not such good, but solve the problem:
def eval_math_expressions(filelist):
for line in filelist:
if re.match('.*[\-|\+|\*|\/].*',line):
lindex=int(filelist.index(line))
line_list=line.split()
exp=[]
for word in line_list:
if re.match('^\(+\d+',word) or re.match('^[\)+|\d+|\-|\+|\*|\/]',word):
exp.append(word)
else:
ready=' '.join(exp)
if ready:
eval_ready=str(eval(ready))
line_new=line.replace(ready,eval_ready)
line=line_new
filelist[lindex]=line
exp=[]
return filelist
Related videos on Youtube
Arsen Manukyan
Updated on June 11, 2022Comments
-
Arsen Manukyan about 2 years
I have a question concerning evaluation of math expression within a string. For example my string is following:
my_str='I have 6 * (2 + 3) apples'
I am wondering how to evaluate this string and get the following result:
'I have 30 apples'
Is the any way to do this?
Thanks in advance.
P.S. python's
eval
function does not help in this case. It raised an error, when trying to evaluate with theeval
function.-
jeffery_the_wind almost 12 years
-
Charles Duffy almost 12 years@jeffery_the_wind not really on point, as this (unlike that) requires discarding non-math parts of the string.
-
-
mgilson almost 12 years@delnan -- if this is
eval
abuse, then what isn'teval
abuse (at which point, shouldn't it be removed from the language completely?). I think this is a completely fine place to useeval
given that the problem is constrained enough to parse the expression to be evaluated out of the input string.