Regular Python

ast module for converting a List-type-string into a real python list

tofusoup429 2017. 5. 7. 09:16

The 'literal_eval()' function in module ast, which stands for Abstract Syntax Trees, is pretty useful when you want to turn "a string-formatted-list" into "a real list".


For example, you have a String aString = "['a','b','c']" and you want aString to be a real list, ['a','b','c'] . That is when you want to use the the 'literal_eval()' in ast module. It's a internal module so you do not need to install it additionally.


Example of Usage

Let me show you simple examples of how to use it.

import ast

aString="[3,4,2,'efe',3]"
aList=ast.literal_eval(aString)

First I defined a list-formatted-string and I want to revert it to a real python list, aList.

print(aList)
>> [3, 4, 2, 'efe', 3]
print(alist[1])
>> 4

Boom. It works.


It also works when a list-format string contains dictionaries-format string such as bString="[{'1':'a'},{'2':'b'}]"

import ast

bString = "[{'1':'a'},{'2':'b'}]"
bList = ast.literal_eval(bString)
print(bList)
>> [{'1': 'a'}, {'2': 'b'}]
print(bList[1])
>> {'2': 'b'}
print(bList[1]['2'])
>> b

Boom. It also works.


The strings were converted into real lists and the dictionaries seamlessly.

Hope this one helps