如何快速解析字符串列表

mat*_*ath 17 python

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

>>> 'abc,foo,bar'.split(',')
['abc', 'foo', 'bar']
Run Code Online (Sandbox Code Playgroud)

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

In: 'abc,"a string, with a comma","another, one"'
Out: ['abc', 'a string, with a comma', 'another, one']
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*lak 38

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)
Run Code Online (Sandbox Code Playgroud)

结果:

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


Gre*_*reg 7

CSV模块应能为你做的