如何快速解析字符串列表

Asked
Viewd35020

17

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

 >>> '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']
 

相关问题:如何我将逗号分隔的字符串解析为列表(caveat)?

35020

2 个答案

39
 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个字符串,带逗号
另外2个,一个
  • 很好。聪明地使用模块:-)

    e-satisDecember 01, 2008 14:33
7

CSV模块应该能够为你做