Split by comma and how to exclude comma from quotes in split … Python

后端 未结 8 1981
长情又很酷
长情又很酷 2020-12-16 13:28

python 2.7 code

cStr = \'\"aaaa\",\"bbbb\",\"ccc,ffffd\"\' 

newStr = cStr.split(\',\')

print newStr 

# result : [\'\"aaaa\"\',\'\"bbbb\"\',\'\"ccc\',\'ffffd\         


        
8条回答
  •  清酒与你
    2020-12-16 13:31

    pyparsing has a builtin expression, commaSeparatedList:

    cStr = '"aaaa","bbbb","ccc,ffffd"' 
    import pyparsing as pp
    print(pp.commaSeparatedList.parseString(cStr).asList())
    

    prints:

    ['"aaaa"', '"bbbb"', '"ccc,ffffd"']
    

    You can also add a parse-time action to strip those double-quotes (since you probably just want the content, not the quotation marks too):

    csv_line = pp.commaSeparatedList.copy().addParseAction(pp.tokenMap(lambda s: s.strip('"')))
    print(csv_line.parseString(cStr).asList())
    

    gives:

    ['aaaa', 'bbbb', 'ccc,ffffd']
    

提交回复
热议问题