No subject

Tim Chase python.list at tim.thechases.com
Tue Dec 11 17:41:27 EST 2007


> How on earth do I convert strings to lists. I have a string
> with a list it in it  and I'm trying to convert it into a
> list. Please help me.
> 
> Ex."[16, 16, 2, 16, 2, 16, 8, 16]"-string to
> [16, 16, 2, 16, 2, 16, 8, 16] -list


If you trust your input, you can just do

 >>> s = "[16, 16, 2, 16, 2, 16, 8, 16]"
 >>> eval(s)
[16, 16, 2, 16, 2, 16, 8, 16]

However, if you don't trust your input quite so much, you can do 
the following:

 >>> [int(i.strip()) for i in s.strip('[]').split(',')]
[16, 16, 2, 16, 2, 16, 8, 16]

It throws away the outer brackets ("strip('[]')"), splits it into 
a list of comma-separated items (".split(',')"), and then 
iterates over each resulting item, stripping of whitespace and 
converting it to an int.

HTH,

-tkc






More information about the Python-list mailing list