472,127 Members | 1,571 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,127 software developers and data experts.

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 1960
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 leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.