string to list of numbers conversion

Tim Williams tim at tdw.net
Sat Nov 11 02:35:21 CET 2006


On 5 Nov 2006 04:34:32 -0800, jm.suresh at no.spam.gmail.com
<jm.suresh at 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?
>

?? I want to convert this into a python tuple of numbers ??

Do you want a python tuple with those numbers ie (1,2, 3,4),  or a
direct evaluation giving a tuple of tuples with those numbers, ie
((1,2), (3,4))

If the former then:

>>> a, l = '((1,2), (3,4), (-5,-6),(12,-13), (a,b), (0.1,0.2))', []
>>> for c in a.split(','):
... 	try:
... 		c = c.replace('(','').replace(')','')
... 		if '.' in c: l.append(float(c))
... 		else: 	l.append(int(c))
... 	except: pass
...
>>> tuple(l)
(1, 2, 3, 4, -5, -6, 12, -13, 0.10000000000000001, 0.20000000000000001)
>>>

Its not so good with floats, but if you are only expecting integers you can use.

>>> a, l = '((1,2), (3,4), (-5,-6),(12,-13), (a,b), (0.1,0.2))', []
>>> for c in a.split(','):
... 	try: l.append(int(c.replace('(','').replace(')','')))
... 	except: pass
...
>>> tuple(l)
(1, 2, 3, 4, -5, -6, 12, -13)
>>>

HTH :)



More information about the Python-list mailing list