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

Question:

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

Asked By: stackyname

||

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.

Answered By: Acccumulation

You can almost use csv for this:

import csv
from io import StringIO
sio = StringIO()
sio.write('"coffee", "water, hot"')
sio.seek(0)
reader = csv.reader(sio)
print(next(reader))
# Prints ['coffee', ' "water', ' hot"']

The problem is that there is a space before the opening quote of "water, hot". If you replace '", "' with ",", then csv will work, and you will get ['coffee', 'water, hot'].

Answered By: cco

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)
Answered By: Jeson Pun

How about:

string = '"coffee", "water, hot"'

stringList = string.split("'")

string = stringList[0]

print(string)
Answered By: rob

You can use re.findall

import re

s = '"coffee", "water, hot"'
re.findall('"(.*?)"', s) # ['coffee', 'water, hot']
Answered By: Iain Shelvington
import ast

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

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

print(result)
Answered By: Kelly Bundy
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.