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

Viewed 29

I have a single quoted string for items separated by comma. Each item surrounded by quotes (") but items also contain comma (,). 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"]

Thank you!

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.

Firstly, I defined a function 'del_quote' to remove unnecessary quotes and spaces. Then I split it taking '",' as a separator. then the result was mapped to remove quotes then converted into list.

def del_quote(s):
return s.replace('"','').strip()

x='"coffee", "water, hot"'
result=list(map(del_quote,x.split('",')))
print(result)
Related