How can I convert a string using re.compile

Emile van Sebille emile at fenx.com
Mon May 13 20:04:58 EDT 2002


young-il sohn
> How can I convert the string 'a = [1 2 3;4 5 6;6 7 8]'
> to other string 'a = [[1,2,3],[4,5,6],[7,8,9]]' ?
>
> Numeric values can have various forms such as 3.2, -4, 3e+3, 3e-2,
> 3E+10, 3E-2 and so on. Space can be inserted in the list.

This seems to work

s = 'a = [1   3.2 -3   ;   4e+3 5e-2  6e+10;  6.2  7 8e+1]'

def nummify(val):
    if val.startswith('['): val =val[1:]
    if val.endswith(']'): val = val[:-1]
    try:
        float(val)
        return val
    except:
        raise ValueError

print s.split('=')[0]+" = "+`[[nummify(jj) for jj in ii.split()] for ii
in s.split('=')[-1].split(";")]`

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list