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

后端 未结 6 1044
心在旅途
心在旅途 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:41

    The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports.

    >>> import shlex
    >>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True)
    >>> my_splitter.whitespace += ','
    >>> my_splitter.whitespace_split = True
    >>> print list(my_splitter)
    ['foo', 'bar', 'one, two', 'three', 'four']
    

    escaped quotes example:

    >>> my_splitter = shlex.shlex('''"test, a",'foo,bar",baz',bar \xc3\xa4 baz''',
                                  posix=True) 
    >>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True 
    >>> print list(my_splitter)
    ['test, a', 'foo,bar",baz', 'bar \xc3\xa4 baz']
    

提交回复
热议问题