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

后端 未结 8 1951
长情又很酷
长情又很酷 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:50

    It will be better to use regex in this case. re.findall('".*?"', cStr) returns exactly what you need

    asterisk is greedy wildcard, if you used '".*"', it would return maximal match, i.e. everything in between the very first and the very last double quote. The question mark makes it non greedy, so '".*?"' returns the smallest possible match.

    0 讨论(0)
  • 2020-12-16 13:54

    You need a parser. You can build your own, or you may be able to press one of the library ones into service. In this case, json could be (ab)used.

    import json
    
    cStr = '"aaaa","bbbb","ccc,ffffd"' 
    jstr = '[' + cStr + ']'
    result = json.loads( jstr)             # ['aaaa', 'bbbb', 'ccc,ffffd']
    result = [ '"'+r+'"' for r in result ] # ['"aaaa"', '"bbbb"', '"ccc,ffffd"']
    
    0 讨论(0)
提交回复
热议问题