469,364 Members | 2,471 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,364 developers. It's quick & easy.

String of integers separated by commas surrounded by square brackets

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>
Dec 11 '07 #1
1 1875
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
Dec 11 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

108 posts views Thread by Bryan Olson | last post: by
5 posts views Thread by Ann Marinas | last post: by
32 posts views Thread by tshad | last post: by
8 posts views Thread by Peter Merwood | last post: by
4 posts views Thread by andreas.fabri | last post: by
reply views Thread by zhoujie | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.