简体   繁体   中英

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

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM