How to convert array string to an array in python

Question:

Im trying to convert an array that ive stored in a mysql database (as a string) to a standard array in python an example of what I mean is:

This is what i get from the database:

"['a',['b','c','d'],'e']" # this is a string in the format of an array that holds strings inside it.

I need to remove the array from the string so that it acts just like a normal array
Any help would be greatly appreciated. I’m not sure if this has been answered elsewhere, sorry if it has I couldn’t find it.
Thanks

Asked By: Riley

||

Answers:

You can use literal_eval in the ast module

>>> from ast import literal_eval
>>> s = "['a',['b','c','d'],'e']"
>>> print(literal_eval(s))
['a', ['b', 'c', 'd'], 'e']
Answered By: Padraic Cunningham

If you can convert those single quotes to double quotes, you can use json parsing.

import json
obj1 = json.loads('["a", ["b", "c", "d"], "e"]')
Answered By: Shashank Agarwal
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.