如何快速解析字符串列表

21

如果我想要使用分隔符字符来拆分一个由单词组成的列表,我可以使用

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

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

2个回答

43
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 另外一个,一个

不错。聪明地使用了模块 :-) - Bite code

8

如果你需要这样的功能,CSV模块可以为你完成。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接