简体   繁体   中英

convert a string which is a list into a proper list python

How do I convert this string which is a list into a proper list?

mylist = "['KYS_Q5Aa8', 'KYS_Q5Aa9']"

I tired this but its not what I was expecting:

print mylist.split()
["['KYS_Q5Aa8',", "'KYS_Q5Aa9']"]

I'd like it like this:

['KYS_Q5Aa8','KYS_Q5Aa9']

Use literal_eval from the ast module:

>>> import ast
>>> ast.literal_eval("['KYS_Q5Aa8', 'KYS_Q5Aa9']")
['KYS_Q5Aa8', 'KYS_Q5Aa9']

Unlike eval , literal_eval is safe to use on user strings or other unknowns string sources. It will only compile strings into basic python data structures -- all others fail.

Alternatively, if your string is just like that (ie, no embedded commas or meaning to parse inside the sub quoted strings) you could coerce split to do what you want do too:

>>> mystring = "['KYS_Q5Aa8', 'KYS_Q5Aa9']"
>>> [e.strip("' ") for e in mystring.strip('[] ').split(',')]
['KYS_Q5Aa8', 'KYS_Q5Aa9']

you can use json library and it's more efficient than eval.

import json
mylist = "['KYS_Q5Aa8', 'KYS_Q5Aa9']"
mylist = json.loads(mylist.replace("'",'\"'))

Json modules evaluates this for you

import json

mylist = '["KYS_Q5Aa8", "KYS_Q5Aa9"]'
arr = json.loads(mylist)

print(arr)
# ['KYS_Q5Aa8', 'KYS_Q5Aa9']

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