Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string into list?

Well, I am using python. And I have case here.

from my api. The following key and value is coming.

games : ["['football','cricket']"]

Now i want to get that football and cricket from coming games value and store in python list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

expected output:

print(games) ==> ["football","circket"]
print(type(games))  ==> <class list>

>Solution :

Perhaps ast.literal_eval function would be useful here. Just pass the string into the function and a list of strings will be returned.

This will be more robust that trying to manipulate the string, as the function is designed to ingest (if you will) key Python data structures as strings; perform a bit of validation to ensure the string is not malicious, and output the associated object.

For example:

import ast

games = ["['football','cricket']"]

ast.literal_eval(games[0])

Output:

['football','cricket']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading