simple string parsing ?

Alex Martelli aleaxit at yahoo.com
Thu Sep 9 18:58:47 CEST 2004


TAG <tonino.greco at gmail.com> wrote:

> Hi,
> 
> I am new to python and would like to parse a string, well acually a
> formula and get the stuff grouped together
> eg:
> 
> if  I have :
> 
> =+GC142*(GC94+0.5*sum(GC96:GC101))
> 
> and I want to get :
> 
> ['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(',
> 'GC96', ':', 'GC101', ')', ')']

>>> import tokenize
>>> import cStringIO
>>> x='=+GC142*(GC94+0.5*sum(GC96:GC101))'
>>> [t[1] for t in
tokenize.generate_tokens(cStringIO.StringIO(x).readline)]
['=', '+', 'GC142', '*', '(', 'GC94', '+', '0.5', '*', 'sum', '(',
'GC96', ':', 'GC101', ')', ')', '']
>>> 

close enough for you...?


Alex



More information about the Python-list mailing list