How to convert string into list?

Viewed 54

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.

expected output:

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

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

this should work

a = ["['football','cricket']"]
out = [val.strip("'") for val in a[0].strip("[|]").split(",")]
print(out)
['football', 'cricket']

I find it unlikely that a api is sending a non-json string. This string is not json because of the single quotes. If you convert them to double quotes, you have a valid json.

list_games = json.loads(games[0].replace("'",'"'))
Related