1

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

PEREZje
  • 1,548
  • 1
  • 7
  • 18
  • 1
    Use the ast module Ex: `ast.literal_eval(table)` – Rakesh May 31 '18 at 11:56
  • @deepakborania https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice – llllllllll May 31 '18 at 11:59
  • 1
    Possible duplicate of [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – Austin May 31 '18 at 12:00

1 Answers1

4

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]]
llllllllll
  • 15,080
  • 4
  • 23
  • 46