如何将逗号分隔的字符串解析为列表(注意事项)?
我需要把一个字符串,比如:
'''foo, bar, "one, two", three four'''
转换成:
['foo', 'bar', 'one, two', 'three four']
我有一种感觉(从#python的提示来看),解决这个问题可能会用到shlex模块。
6 个回答
5
你可能还想看看csv这个模块。我没有试过,但看起来你的输入数据更像CSV格式,而不是shell语法(shlex是用来解析shell语法的)。
42
这要看你想要多复杂了……你想允许多种类型的引号吗?那转义引号呢?
你的语法看起来很像常见的CSV文件格式,这种格式在Python的标准库中是支持的:
import csv
reader = csv.reader(['''foo, bar, "one, two", three four'''], skipinitialspace=True)
for r in reader:
print r
输出结果:
['foo', 'bar', 'one, two', 'three four']
希望这对你有帮助!
27
shlex模块的解决方案可以处理转义的引号,也就是说一个引号可以用来转义另一个引号,还有很多其他复杂的功能,都是shell支持的。
>>> 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']
转义引号的例子:
>>> 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']