I have a string which I want to convert to a list where each element is delimited by commas.
For example 'test1,"test2,test3",test4'
will become ['test1', 'test2 test3', 'test4']
Note that I do not want to split test2
and test3
I have a string which I want to convert to a list where each element is delimited by commas.
For example 'test1,"test2,test3",test4'
will become ['test1', 'test2 test3', 'test4']
Note that I do not want to split test2
and test3
Like the answer of TigerhawkT3, i use csv.reader
too, but with 2 more parameters.
import csv
src_text = 'test1,"test2,test3",test4'
r = csv.reader([src_text], delimiter= ',', quotechar='"')
converted_list = next(r)
Output
>>> print converted_list
['test1', 'test2,test3', 'test4']
What you have there is a row from a CSV file. Use csv.reader
.
>>> import csv
>>> lines = ['test1,"test2,test3",test4', 'testa,"testb,testc",testd']
>>> r = csv.reader(lines)
>>> list(r)
[['test1', 'test2,test3', 'test4'], ['testa', 'testb,testc', 'testd']]
You can split()
it by "
first, replace the commas with spaces, strip()
trailing whitespace, and remove empty elements (when the double quote is at the end). This would require quite a lot of iterations. Look at @TigerhawkT3's answer.
def split_string(s):
ret = s.split('"')
ret = [ " ".join(x.split(",")) for x in ret ]
ret = [x.strip() for x in ret]
ret = [ x for x in ret if x != ""]
return ret