[Tutor] Convert a string of numbers to a list

Vern Ceder vceder at canterburyschool.org
Sat Feb 28 03:32:02 CET 2009


Kyle Kwaiser wrote:

> x = ['[335, 180, 201, 241, 199]\r\n']
> y = map( int, x[0].strip( '[]\r\n' ).split(  ', '  ) ) #need an index here
> print y
> [335, 180, 201, 241, 199]

I realize it's not totally secure, but if your string really is in that 
format (i.e., a representation of a list), you COULD just use eval():

 >>> x = '[335, 180, 201, 241, 199]\r\n'
 >>> y = eval(x.strip())
 >>> print y
[335, 180, 201, 241, 199]
 >>>

Regards,
Vern Ceder


More information about the Tutor mailing list