Transform comma separated string into a list but ignore comma in quotes

纵饮孤独 提交于 2019-12-04 08:47:04

Instead of a regular expression, you might be better off using the csv module since what you are dealing with is a CSV string:

from cStringIO import StringIO
from csv import reader

file_like_object = StringIO("1,,2,'3,4'")
csv_reader = reader(file_like_object, quotechar="'")
for row in csv_reader:
    print row

This results in the following output:

['1', '', '2', '3,4']

pyparsing includes a predefined expression for comma-separated lists:

>>> from pyparsing import commaSeparatedList
>>> s = "1,,2'3,4'"
>>> print commaSeparatedList.parseString(s).asList()
['1', '', "2'3", "4'"]

Hmm, looks like you have a typo in your data, missing a comma after the 2:

>>> s = "1,,2,'3,4'"
>>> print commaSeparatedList.parseString(s).asList()
['1', '', '2', "'3,4'"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!