Skip to content
Advertisement

How to convert string data having comma to a list in python

I have a string as below:

'["Product1, "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]'

I want to convert this string into a list, but when I try to do this using .split(",") I am getting an list as below:

["Product1", "Product1", "Product2", "Product1", Product2", Product3", "Product3", "Product4"]

I would like to have a list as:

["Product1", "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]

How can I achieve this?

Advertisement

Answer

The initial list has " missing in first word.

We can use ast module in this case –

    import ast
    list1='["Product1", "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]'
    
    list2=ast.literal_eval(list1)
    print(list2)

Other alternative would be to make use of json module

    import json
    list1='["Product1", "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]'
    
    list2=json.loads(list1)
    print(list2)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement