String of integers separated by commas surrounded by square brackets to a list (was Re:)
Larry Bates
larry.bates at websafe.com
Tue Dec 11 18:32:35 EST 2007
Tim Couper wrote:
> It looks like you have a string which starts and ends with square
> brackets and is a repeated group of (integer, comma (and perhaps
> space)). What you don't have is a "string with a list in it" :-)
>
> One solution:
>
> s="[16, 16, 2, 16, 2, 16, 8, 16]"
>
> mylist=[int(s.strip()) for s in s[1:-1].split(',')]
>
> Tim
>
> Dr Tim Couper
> CTO, SciVisum Ltd
>
> www.scivisum.co.uk
>
>
>
> katie smith wrote:
>> 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
>>
>> ------------------------------------------------------------------------
>> Looking for last minute shopping deals? Find them fast with Yahoo!
>> Search.
>> <http://us.rd.yahoo.com/evt=51734/*http://tools.search.yahoo.com/newsearch/category.php?category=shopping>
>>
If you know the string doesn't contain anything evil (that is you control where
it comes from) you can also do:
mylist=eval(s)
-Larry
More information about the Python-list
mailing list