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
We can create a copy of an array by using the assignment operator (=). In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn't.
STEP 1: Declare and initialize an array. STEP 2: Declare another array of the same size as of the first one. STEP 3: Loop through the first array from 0 to length of the array and copy an element from the first array to the second array that is arr1[i] = arr2[i].
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']
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"]')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With