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