Evaluating the contents of a string

Timothy Grant tjg at exceptionalminds.com
Mon Mar 19 14:11:08 EST 2001


On Mon, Mar 19, 2001 at 10:48:13AM -0700, Aaron Ginn wrote:
> 
> Is there a simple way to evaluate the contents of a string assuming
> that string contains only nunbers and mathematical operators?
> 
> For example, I'm parsing a file that contains expressions contained in 
> parantheses such the following:
> 
> 12 net64 a vss vss n w=1.1u l=0.5u ad=(1.1 * 1.15) as=(1.1 * 1.15)
>                                       ^^^^^^^^^^^^    ^^^^^^^^^^^^
> 
> I'm using a stack to determine when an expression can be evaluated
> (i.e., when a closing paranthesis is found), and I'm storing the
> contents of the parantheses in a string.  When the first closing
> parenthesis is found in the example above, the string to be evaluated
> will be '1.1 * 1.15'.  Is there a module that will mathematically
> evaluate this string?

Using your example string above, the following appears to work:

>>> import re
>>> x = re.findall(r'[a-z][a-z]=\(.*?\)', x)
>>> for y in x:
...     exec y
... 
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'ad', 'as', 're',
'x', 'y', 'z']
>>> 
>>> print ad
1.265
>>> print as
1.265
>>> 


-- 
Stand Fast,
    tjg.

Timothy Grant                         tjg at exceptionalminds.com
Red Hat Certified Engineer            www.exceptionalminds.com
Avalon Technology Group, Inc.         <><       (503) 246-3630
>>>>>>>>>>>>>Linux, because rebooting is *NOT* normal<<<<<<<<<
>>>>This machine was last rebooted:  61 days 23:25 hours ago<<




More information about the Python-list mailing list