【问题标题】:How to quickly parse a list of strings如何快速解析字符串列表
【发布时间】:2010-09-24 18:13:18
【问题描述】:

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

>>> '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)?

【问题讨论】:

    标签: python


    【解决方案1】:

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

    【讨论】:

    • 此链接已过时。
    【解决方案2】:
    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另一个,一个

    【讨论】:

    • 不错的一个。智能使用模块:-)
    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 2023-02-22
    • 1970-01-01
    • 2020-03-26
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多