String of integers separated by commas surrounded by square brackets

T

Tim Couper

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
 
L

Larry Bates

Tim said:
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 said:
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 know the string doesn't contain anything evil (that is you control where
it comes from) you can also do:

mylist=eval(s)

-Larry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top