Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array string to an array in python [duplicate]

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

like image 397
Riley Avatar asked Aug 29 '14 16:08

Riley


People also ask

How do you duplicate an array in Python?

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.

How do you create an array from an existing array in Python?

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].


2 Answers

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']
like image 155
Padraic Cunningham Avatar answered Oct 02 '22 09:10

Padraic Cunningham


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"]')
like image 40
Shashank Agarwal Avatar answered Oct 02 '22 07:10

Shashank Agarwal