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