Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an Array, converted to a String, back to an Array

I recently found an interesting behaviour in python due to a bug in my code. Here's a simplified version of what happened:

a=[[1,2],[2,3],[3,4]]
print(str(a))
console:
"[[1,2],[2,3],[3,4]]"

Now I wondered if I could convert the String back to an Array.Is there a good way of converting a String, representing an Array with mixed datatypes( "[1,'Hello',['test','3'],True,2.532]") including integers,strings,booleans,floats and arrays back to an Array?

like image 277
frameworker Avatar asked Jan 07 '16 12:01

frameworker


People also ask

Can we convert string array to string?

We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.


1 Answers

There's always everybody's old favourite ast.literal_eval

>>> import ast
>>> x = "[1,'Hello',['test','3'],True,2.532]"
>>> y = ast.literal_eval(x)
>>> y
[1, 'Hello', ['test', '3'], True, 2.532]
>>> z = str(y)
>>> z
"[1, 'Hello', ['test', '3'], True, 2.532]"
like image 163
Paul Rooney Avatar answered Oct 22 '22 00:10

Paul Rooney