12

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
  • 3,675
  • 3
  • 15
  • 29

2 Answers2

32

You can use ast.literal_eval

>>> from ast import literal_eval
>>> s = "['a',['b','c','d'],'e']"
>>> print(literal_eval(s))
['a', ['b', 'c', 'd'], 'e']
Scorpion_God
  • 1,481
  • 10
  • 15
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312
6

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,591
  • 1
  • 22
  • 23