如何快速解析字符串列表

时间:2008-12-01 13:51:43

标签: 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)?

2 个答案:

答案 0 :(得分:37)

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

答案 1 :(得分:7)

CSV module应该能够为您做到这一点