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

44

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']
6
  • 1
    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 Commented Aug 29, 2014 at 16:22
  • @JoranBeasley Do you know how i would use python to store json in the database
    – Riley
    Commented Aug 29, 2014 at 16:27
  • @RileyThe15YearOld json.dumps() will turn your array into a JSON string, and json.loads() will turn it back into a Python array. Commented Aug 29, 2014 at 16:32
  • @TheSoundDefense id just prefer to keep it as an array really
    – Riley
    Commented Aug 29, 2014 at 16:35
  • @RileyThe15YearOld ok, but it's not going to be as reliable or safe, I don't think. Commented Aug 29, 2014 at 16:36
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
  • The accepted answer is a better solution. Commented Jul 7, 2021 at 1:33
  • 1
    This one also good solution. Commented Nov 13, 2021 at 12:26
  • I think your solution is better.
    – Dwa
    Commented Jun 11, 2022 at 21:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.