3

I have a string that represents a list:

"[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"

I would like to turn that litteral string into an actual list. I suppose to could regex out the numbers and loop over then (append()) but is there an easier way? Not sure how I would set that up as a regex.

Elliot A.
  • 1,511
  • 2
  • 14
  • 19
Ben Keating
  • 8,206
  • 9
  • 37
  • 37
  • 1
    Looking like there are a *lot* of ways to do this. This page in it's entirety should have an 'accept answer' check mark. Keep them coming. – Ben Keating Mar 06 '11 at 23:59

5 Answers5

12

Use ast.literal_eval.

>>> import ast
>>> i = ast.literal_eval('[22, 33, 36, 41, 46, 49, 56]')
>>> i[3]
41
Ben Keating
  • 8,206
  • 9
  • 37
  • 37
mouad
  • 67,571
  • 18
  • 114
  • 106
4

Yet another way:

import json
x=json.loads("[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]")
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

If your actual string is

s = "[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"

then this will do the trick:

[int(n) for n in s[1:-1].split(', ')]
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

Try this:

sl = "[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"
sl = sl.lstrip('[')
sl = sl.rstrip(']')
sl = sl.split(',')

Ugly and hacky, but it'll work!

mattdeboard
  • 700
  • 1
  • 7
  • 17
  • 2
    ugly, hacky, and delivers a list of `str` objects -- should be `int` objects – John Machin Mar 07 '11 at 00:55
  • In my case I have `;`-separated values in the string, so it looks like this is only way I can do it. I mean, with `split`. `ast.literal_eval` doesn't support any manipulation of that kind. – Ricky Robinson Jan 30 '13 at 18:11
0

You can use the built-in eval http://docs.python.org/library/functions.html#eval

>>> lst = eval("[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]")
>>> type(lst)
<type 'list'>
>>> lst[0]
22
ssoler
  • 4,884
  • 4
  • 32
  • 33