Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

covert 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']
like image 921
Boosted_d16 Avatar asked Feb 12 '14 17:02

Boosted_d16


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

Which method is used to convert a list of strings to a string?

The most pythonic way of converting a list to string is by using the join() method. The join() method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string.


1 Answers

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']
like image 180
dawg Avatar answered Oct 26 '22 12:10

dawg