考虑以下字符串:
'538.48,0.29,"533.59 - 540.00","AZO",102482,"+0.05%","N/A",0.00,535.09,"AutoZone, Inc. Co",538.77,"N/A"'
我需要将其拆分为一个列表,如下所示:
[538.48, 0.29, "533.59 - 540.00", "AZO", 102482, "+0.05%" , "N/A", 0.00, 535.09, "AutoZone, Inc. Co", 538.77, "N/A"]
问题是我无法使用list.split(',')
因为第10个字段中有逗号。问题是当任意字段可能有逗号时,如何最好地将原始字符串拆分成列表?
答案 0 :(得分:2)
使用csv
module而不是尝试自己拆分它,它处理引用的值,包括包含分隔符的引用值,开箱即用:
>>> import csv
>>> from pprint import pprint
>>> data = '538.48,0.29,"533.59 - 540.00","AZO",102482,"+0.05%","N/A",0.00,535.09,"AutoZone, Inc. Co",538.77,"N/A"'
>>> reader = csv.reader(data.splitlines())
>>> pprint(next(reader))
['538.48',
'0.29',
'533.59 - 540.00',
'AZO',
'102482',
'+0.05%',
'N/A',
'0.00',
'535.09',
'AutoZone, Inc. Co',
'538.77',
'N/A']
请注意'AutoZone, Inc. Co'
列值。
如果您正在从文件中读取此数据,请直接将文件对象传递给csv.reader()
对象,而不是将其传递给字符串序列。
您甚至可以通过设置quoting=csv.QUOTE_NONNUMERIC
将数值(未引用的任何内容)解释为浮点值:
>>> reader = csv.reader(data.splitlines(), quoting=csv.QUOTE_NONNUMERIC)
>>> pprint(next(reader))
[538.48,
0.29,
'533.59 - 540.00',
'AZO',
102482.0,
'+0.05%',
'N/A',
0.0,
535.09,
'AutoZone, Inc. Co',
538.77,
'N/A']