Mahesha999 Mahesha999 - 2 months ago 9
Python Question

Converting to/getting original list object from string representation of original list object in python

I want to convert string representation of arbitrary list back to the original-like list object as explained in the code below:

list1 = [1,2,3,4]
list1str = str(list1)
str2list1 = list1str[1:-1].split(",") #stripping off square brackets from [1,2,3,4] and then splitting
print(list1) #[1,2,3,4]
print(str(list1)) #[1,2,3,4]
print(str2list1) #['1', ' 2', ' 3', ' 4']
#Notice that the elements are of string types.
#Also there is a prefix empty space in ' 2' (and also in ' 3' and ' 4')
# --> I will like str2list1 to be ['1', ' 2', ' 3', ' 4']


Also if we are dealing with nested lists:

list2 = [1,2,['a','b'],4]
list2str = str(list2)
str2list2 = list2str[1:-1].split(",")
print(list2) #[1, 2, ['a', 'b'], 4]
print(str(list2)) #[1, 2, ['a', 'b'], 4]
print(str2list2) #['1', ' 2', " ['a'", " 'b']", ' 4']
# --> I will like str2list2 to be [1, 2, ['a', 'b'], 4]


How can I get exact the original list from its string representation?

Answer

You can try:

>>> import ast
>>> ast.literal_eval("[1,2,['a','b'],4]")
[1, 2, ['a', 'b'], 4]