Skip to content Skip to sidebar Skip to footer

Converting A String That Represents A List, Into An Actual List Object

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,

Solution 1:

Use ast.literal_eval.

>>>import ast>>>i = ast.literal_eval('[22, 33, 36, 41, 46, 49, 56]')>>>i[3]
41

Solution 2:

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]")

Solution 3:

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(', ')]

Solution 4:

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!

Solution 5:

You can use the built-in evalhttp://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

Post a Comment for "Converting A String That Represents A List, Into An Actual List Object"