Convert array converted to string back to array

I recently found interesting behavior in python due to an error in my code. Here is 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 was thinking, can I convert String back to Array.Is there a good way to convert String representing an array with mixed data types ( "[1,'Hello',['test','3'],True,2.532]"), including integers, strings, booleans, float and arrays back to array?

+4
source share
2 answers

Always every old beloved 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]"
+11
source

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
+2
source

Source: https://habr.com/ru/post/1623262/


All Articles