Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

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']

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...