0

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

Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38
Prats
  • 1,745
  • 4
  • 24
  • 28

3 Answers3

2

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']
qvpham
  • 1,896
  • 9
  • 17
1

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']]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • I would like to know what is wrong or unhelpful about my answer to make it deserve a downvote, so that I can improve it. – TigerhawkT3 May 30 '16 at 09:19
0

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
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38