Search code examples
pythonstringlist

Convert string into list Python


So I've got some data which I scraped from a website and it looks like this:

table = '[['January 2010',1368,719],['February 2010',1366,729] ... ['April 2018',1429,480],['Today',1440,448]]'

It's already formatted pretty well but how would I go about converting this string into a list of lists that looks the exact same but simply has a list datatype instead of string?

I tried just converting the datatype but that didn't give me the right answer:

> print(list(table))
> ['[', '[', "'", 'J', 'a' ... '4', '4', '8', ']', ']']

Thanks in advance


Solution

  • Use ast.literal_eval:

    In [24]: import ast
    
    In [25]: ast.literal_eval(table)
    Out[25]: 
    [['January 2010', 1368, 719],
     ['February 2010', 1366, 729],
     ['April 2018', 1429, 480],
     ['Today', 1440, 448]]