string to list of numbers conversion

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Nov 5 09:53:21 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?

This is a possibile solution, no input errors are taken into account:

>>> s = '((1,2), (3,4), (-5,9.2))'
>>> from string import maketrans
>>> tab = maketrans("(), ", " "*4)
>>> s.translate(tab)
'  1 2    3 4    -5 9.2  '
>>> l = s.translate(tab).split()
>>> l
['1', '2', '3', '4', '-5', '9.2']
>>> l2 = map(float, l)
>>> l2
[1.0, 2.0, 3.0, 4.0, -5.0, 9.1999999999999993]
>>> # This is partition(l2, 2)
>>> [l2[i:i+2] for i in xrange(0, len(l2), 2)]
[[1.0, 2.0], [3.0, 4.0], [-5.0, 9.1999999999999993]]

Bye,
bearophile




More information about the Python-list mailing list