string to list of numbers conversion

Frederic Rentsch anthra.norell at vtxmail.ch
Mon Nov 6 04:22:31 EST 2006


jm.suresh at no.spam.gmail.com wrote:
> Hi,
>   I have a string '((1,2), (3,4))' and I want to convert this into a
> python tuple of numbers. But I do not want to use eval() because I do
> not want to execute any code in that string and limit it to list of
> numbers.
>   Is there any alternative way?
>
> Thanks.
> Suresh
>
>   
s = '((1,2), (3,4))'
separators = re.compile ('\(\s*\(|\)\s*,\s*\(|\)\s*\)')
tuple ([(float (n[0]), float (n[1])) for n in [pair.split (',') for pair 
in separators.split (s) if pair]])
((1.0, 2.0), (3.0, 4.0))

Frederic





More information about the Python-list mailing list