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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With