How to convert string into list?

Question:

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>
Asked By: dummy first

||

Answers:

this should work

a = ["['football','cricket']"]
out = [val.strip("'") for val in a[0].strip("[|]").split(",")]
print(out)
['football', 'cricket']
Answered By: Lucas M. Uriarte

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']
Answered By: S3DEV

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("'",'"'))
Answered By: TheMaster
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.