I have a string as below:
JavaScript
x
2
1
'["Product1, "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]'
2
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:
JavaScript
1
2
1
["Product1", "Product1", "Product2", "Product1", Product2", Product3", "Product3", "Product4"]
2
I would like to have a list as:
JavaScript
1
2
1
["Product1", "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]
2
How can I achieve this?
Advertisement
Answer
The initial list has "
missing in first word.
We can use ast module in this case –
JavaScript
1
6
1
import ast
2
list1='["Product1", "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]'
3
4
list2=ast.literal_eval(list1)
5
print(list2)
6
Other alternative would be to make use of json module
JavaScript
1
6
1
import json
2
list1='["Product1", "Product1, Product2", "Product1, Product2, Product3", "Product3, Product4"]'
3
4
list2=json.loads(list1)
5
print(list2)
6