Evaluate math expression within string

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.

PS 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.


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.


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
链接地址: http://www.djcxy.com/p/63078.html

上一篇: R Sweave输出错误

下一篇: 评估字符串内的数学表达式