19

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

0

2 Answers 2

45

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']
Sign up to request clarification or add additional context in comments.

6 Comments

while this is definately right(+1) ... he may want to consider changing the format that he is storing in the db to json or something
@JoranBeasley Do you know how i would use python to store json in the database
@RileyThe15YearOld json.dumps() will turn your array into a JSON string, and json.loads() will turn it back into a Python array.
@TheSoundDefense id just prefer to keep it as an array really
@RileyThe15YearOld ok, but it's not going to be as reliable or safe, I don't think.
|
13

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

3 Comments

The accepted answer is a better solution.
This one also good solution.
I think your solution is better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.