16

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

Riley
  • 4,122
  • 3
  • 16
  • 30

2 Answers2

38

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']
wkeithvan
  • 1,755
  • 1
  • 12
  • 17
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
12

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"]')
Shashank Agarwal
  • 2,769
  • 1
  • 22
  • 24