frameworker
frameworker

Reputation: 378

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?

Upvotes: 13

Views: 10631

Answers (2)

Rockybilly
Rockybilly

Reputation: 4520

ast.literal_eval is better. Just to mention, this is also a way.

a=[[1,2],[2,3],[3,4]]
string_list = str(a)
original_list = eval(string_list)
print original_list == a
# True

Upvotes: 4

Paul Rooney
Paul Rooney

Reputation: 21619

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

Upvotes: 21

Related Questions