Reputation: 13
how do I convert a string of integer list into a list of integers?
Example input: (type: string)
"[156, 100, 713]"
Example conversion: (type: list of int)
[156, 100, 713]
Upvotes: 1
Views: 134
Reputation: 2431
>>> import json
>>> a = "[156, 100, 713]"
>>> json.loads(a)
[156, 100, 713]
Upvotes: 2
Reputation: 309841
use ast.literal_eval
on it and you're done. Here you don't have all the security issues of regular eval
and you don't need to worry about making sure your string is well formed, etc. Of course, if you really want to parse this thing yourself, you can do it with a pretty simple list-comprehension:
s = "[156, 100, 713]"
print [ int(x) for x in s.translate(None,'[]').split(',') ]
Upvotes: 2
Reputation: 29093
Try this:
import ast
res = ast.literal_eval('[156, 100, 713]')
Read more about ast.literal_eval in python docs.
Upvotes: 5