简体   繁体   中英

Convert string of list into list of int

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]

Try this:

import ast
res = ast.literal_eval('[156, 100, 713]')

Read more about ast.literal_eval in python docs.

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(',') ]
>>> import json
>>> a = "[156, 100, 713]"
>>> json.loads(a)
[156, 100, 713]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM