Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Evaluate math expression within string [duplicate]

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 the eval function.

like image 917
Arsen Manukyan Avatar asked Aug 28 '12 16:08

Arsen Manukyan


1 Answers

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.

like image 60
Burhan Khalid Avatar answered Nov 11 '22 23:11

Burhan Khalid