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,260
  • 2
  • 12
  • 19
Ben Keating
  • 7,656
  • 9
  • 36
  • 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
  • 7,656
  • 9
  • 36
  • 37
mouad
  • 63,741
  • 17
  • 112
  • 105
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
  • 777,569
  • 165
  • 1,697
  • 1,613
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
  • 342,876
  • 71
  • 713
  • 819
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
  • 690
  • 1
  • 6
  • 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,436
  • 4
  • 30
  • 33