string to list of numbers conversion

Gerard Flanagan grflanagan at yahoo.co.uk
Sun Nov 5 08:00:35 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?


Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '((1,2), (3,4))'
>>> s = filter(lambda char: char not in ')(', s)
>>> s
'1,2, 3,4'
>>> s = s.split(',')
>>> s
['1', '2', ' 3', '4']
>>> s = map(float, s)
>>> s
[1.0, 2.0, 3.0, 4.0]
>>> t1 = s[::2]
>>> t1
[1.0, 3.0]
>>> t2 = s[1::2]
>>> t2
[2.0, 4.0]
>>> zip(t1, t2)
[(1.0, 2.0), (3.0, 4.0)]
>>>

Gerard




More information about the Python-list mailing list