Search code examples
pythonstringlisttype-conversion

Is there a clever way to convert a compex string to multiple lists in Python 3


Here is a string :

[[15,"name",12],[2002,"another name",345]]

My actual string is much longer and stems from a text file. The structure is repetitive as indicated in the sample.

I want to convert this string to 3 different lists, namely:

int_list1 = [15, 2002]
str_list = ['name', 'another name']
int_list2 = [12, 345]

I can manage this by using the re module with re.findall() method


Solution

  • Use a list comprehensions with ast.literal_eval()

    import ast
    
    sample_string = '[[15,"name",12],[2002,"another name",345]]'
    parsed_list = ast.literal_eval(sample_string)
    
    int_list1 = [item[0] for item in parsed_list]
    str_list = [item[1] for item in parsed_list]
    int_list2 = [item[2] for item in parsed_list]
    
    print("Integer List 1:", int_list1)
    print("String List:", str_list)
    print("Integer List 2:", int_list2)
    

    Output

    Integer List 1: [15, 2002]
    String List: ['name', 'another name']
    Integer List 2: [12, 345]