Hidden string which is a list in the correct python list

How do I convert this string which is a list to a valid list?

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

I am tired of this, but this is not what I expected:

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

I would like it:

['KYS_Q5Aa8','KYS_Q5Aa9']

thanks

+4
source share
3 answers

Use literal_eval from ast module:

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

In contrast eval, literal_eval is safe to use in custom strings or other unknown string sources. It will compile strings only into the underlying python data structures - everyone else fails.

, (.. ), , :

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

json-, , eval.

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

You can use eval:

>>> mylist = "['KYS_Q5Aa8', 'KYS_Q5Aa9']"
>>> mylist = eval(mylist)
>>> mylist
['KYS_Q5Aa8', 'KYS_Q5Aa9']

Please note that you should not use evalfor untrusted strings (i.e. everything that you do not create yourself).

0
source

Source: https://habr.com/ru/post/1526592/


All Articles