How can i parse a comma delimited string into a list (caveat)?

后端 未结 6 1050
心在旅途
心在旅途 2020-12-05 14:11

I need to be able to take a string like:

\'\'\'foo, bar, \"one, two\", three four\'\'\'

into:

[\'foo\', \'bar\', \'one, two         


        
6条回答
  •  渐次进展
    2020-12-05 14:48

    You could do something like this:

    >>> import re
    >>> pattern = re.compile(r'\s*("[^"]*"|.*?)\s*,')
    >>> def split(line):
    ...  return [x[1:-1] if x[:1] == x[-1:] == '"' else x
    ...          for x in pattern.findall(line.rstrip(',') + ',')]
    ... 
    >>> split("foo, bar, baz")
    ['foo', 'bar', 'baz']
    >>> split('foo, bar, baz, "blub blah"')
    ['foo', 'bar', 'baz', 'blub blah']
    

提交回复
热议问题