本文介绍了如何将逗号分隔的字符串解析为列表(警告)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要能够接受这样的字符串:
'''foo, bar, "一,二",三四'''
进入:
['foo', 'bar', '一,二','三四']
我有一种感觉(来自#python 的提示)解决方案将涉及 shlex 模块.
解决方案
shlex 模块解决方案允许转义引号,一个引号转义另一个,以及 shell 支持的所有花哨的东西.
>>>进口shlex>>>my_splitter = shlex.shlex('''foo, bar, "一,二",三四''',posix=True)>>>my_splitter.whitespace += ','>>>my_splitter.whitespace_split = True>>>打印列表(my_splitter)['foo', 'bar', '一,二','三','四']转义引号示例:
>>>my_splitter = shlex.shlex('''"test, a",'foo,bar",baz',bar xc3xa4 baz''',posix=真)>>>my_splitter.whitespace = ',' ;my_splitter.whitespace_split = True>>>打印列表(my_splitter)['test, a', 'foo,bar",baz', 'bar xc3xa4 baz']I need to be able to take a string like:
'''foo, bar, "one, two", three four'''
into:
['foo', 'bar', 'one, two', 'three four']
I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
解决方案
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 xc3xa4 baz''',
posix=True)
>>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True
>>> print list(my_splitter)
['test, a', 'foo,bar",baz', 'bar xc3xa4 baz']
这篇关于如何将逗号分隔的字符串解析为列表(警告)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!