Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"]

like image 222
stackyname Avatar asked Oct 20 '25 14:10

stackyname


2 Answers

You can split on separators that contain more than one character. '"coffee", "water, hot"'.split('", "') gives ['"coffee','water, hot"']. From there you can remove the initial and terminal quote mark.

like image 108
Acccumulation Avatar answered Oct 23 '25 05:10

Acccumulation


import ast

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

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

print(result)
like image 34
Kelly Bundy Avatar answered Oct 23 '25 04:10

Kelly Bundy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!