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

Question:

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?

Asked By: Rohan Gokhale

||

Answers:

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)
Answered By: kehsihba19
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.