1

i have a string like this

sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]"

how do i convert that to list? I am expecting the output to be list, like this

output=[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]

I am aware of split() function but in this case if i use

sample.split(',')

it will take in the [ and ] symbols. Is there any easy way to do it?

EDIT Sorry for the duplicate post..I didn't see this post until now Converting a string that represents a list, into an actual list object

Community
  • 1
  • 1
Chris Aung
  • 9,152
  • 33
  • 82
  • 127

2 Answers2

4

If you're going to be dealing with Python-esque types (such as tuples for instance), you can use ast.literal_eval:

from ast import literal_eval

sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]"

sample_list = literal_eval(sample)
print type(sample_list), type(sample_list[0]), sample_list
# <type 'list'> <type 'int'> [2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

you can use standard string methods with python:

output = sample.lstrip('[').rstrip(']').split(', ')

if you use .split(',') instead of .split(',') you will get the spaces along with the values!

you can convert all values to int using:

output = map(lambda x: int(x), output)

or load your string as json:

import json
output = json.loads(sample)

as a happy coincidence, json lists have the same notation as python lists! :-)

zmo
  • 24,463
  • 4
  • 54
  • 90
  • thanks a lot!I didn't know about `lstrip` and `rstrip` until now.. very useful stuff. – Chris Aung Jun 26 '13 at 13:15
  • @ChrisAung Actually calling `sample.strip('[]')` is equivalent to `sample.lstrip('[').rstrip(']')`. Most of the method that have `r` and `l` versions also have a version without prefix that works on both ends of the string. – Bakuriu Jun 26 '13 at 13:23
  • @Bakuriu you're right about that, but I prefer making it explicit when I can, so that a string that is not a good formatted list will just break. Explicit is better than implicit ;-). – zmo Jun 26 '13 at 13:27