我想用“,”分割一个字符串。 正如预期的那样,'split' 函数适用于以下 'example1'。
example1 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc'"
example1.split(",")
Result: ['1', "'aaa'", '337.5', '17195', '.02', '0', '0', "'yes'", "'abc'"]
但是,这里我有一个场景,单引号内有逗号,我不想在其上拆分。
example2 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc, def, xyz'"
example2.split(",")
Result: ["1,'aaa',337.5,17195,.02,0,0,'yes','abc,", 'def,', "xyz'"]
但我试图得到这个结果:
['1', "'aaa'", '337.5', '17195', '.02', '0', '0', "'yes'", "'abc, def, xyz'"]
如何使用字符串拆分功能实现这一点?
最佳答案
您应该首先尝试使用内置函数或标准库将数据作为列表 读入,例如通过csv
直接从CSV 文件中读入。模块。
如果您的字符串来自您无法控制的来源,添加左方括号和右方括号可提供有效的列表
,因此您可以使用ast.literal_eval
。 :
from ast import literal_eval
example2 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc, def, xyz'"
res = literal_eval(f'[{example2}]')
# [1, 'aaa', 337.5, 17195, 0.02, 0, 0, 'yes', 'abc, def, xyz']
这会根据需要将数字数据转换为整数/ float 。如果您想将它们保留为字符串,按照@JonClements 的评论,您可以传递给 csv.reader
:
import csv
res = next(csv.reader([example2], quotechar="'"))
# ['1', 'aaa', '337.5', '17195', '.02', '0', '0', 'yes', 'abc, def, xyz']
关于Python字符串拆分,处理单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54037892/