如果我想拆分由分隔符分隔的单词列表,我可以使用
>>> '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']
相关问题:如何将逗号分隔的字符串解析为列表(警告)?
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
该CSV模块应能为你做的