python - 如何快速解析字符串列表

标签 python

如果我想拆分由分隔符分隔的单词列表,我可以使用

>>> 'abc,foo,bar'.split(',')
['abc', 'foo', 'bar']

但是,如果我还想处理可以包含分隔符的带引号的字符串,如何轻松快速地做同样的事情呢?

In: 'abc,"a string, with a comma","another, one"'
Out: ['abc', 'a string, with a comma', 'another, one']

相关问题:How can i parse a comma delimited string into a list (caveat)?

最佳答案

import csv

input = ['abc,"a string, with a comma","another, one"']
parser = csv.reader(input)

for fields in parser:
  for i,f in enumerate(fields):
    print i,f    # in Python 3 and up, print is a function; use: print(i,f)

结果:

0 abc
1 a string, with a comma
2 another, one

关于python - 如何快速解析字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/330900/

相关文章:

python - 如何使用列表将用户定义的函数更改为pandas系列

python - conda 在 python2.7 环境中安装 basemap 给出运行时错误 R6034

python - 使用 XlsxWriter 将 pandas 图表插入 Excel 文件

python - django.db.utils.NotSupportedError : PostgreSQL 12 or later is required (found 11. 19)

python - 零个或一个量词 (`?` ) 似乎并不贪婪

python - 在 pandas 中使用 bool 数组索引对象的最惯用方法是什么?

python - 尝试将 dict_values 转换为 ipdb 中的列表时出错

python - pyspark.ml : Type error when computing precision and recall

python - 错误 :document must be an instance of dict, bson.son.SON、bson.raw_bson.RawBSONDocument 或继承自 collections.MutableMapping 的类型

python - 为什么这个 sqlite python 3x 代码与 python 27 不兼容