Skip to content
Advertisement

How to convert comma separated string to list that contains comma in items in Python?

I have a string for items separated by comma. Each item is surrounded by quotes (“), but the items can also contain commas (,). So using split(',') creates problems.

How can I split this text properly in Python?

An example of such string

"coffee", "water, hot"

What I want to achieve

["coffee", "water, hot"]

Advertisement

Answer

import ast

s = '"coffee", "water, hot"'

result = ast.literal_eval(f'[{s}]')

print(result)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement