我在尝试使用多个变体的Python str时遇到问题,但似乎都没有用。 这是我的问题:
string = '18.0 8 307.0 130.0 3504. 12.0 70 1\t"chevrolet chevelle malibu"'
我想处理这个字符串,并得到如下返回:
['18.0','8','307.0','130.0','3504.','12.0','70','1','"chevrolet chevelle malibu"']
或类似这样:
['18.0','8','307.0','130.0','3504.','12.0','70','1','chevrolet chevelle malibu']
我尝试使用re.complie(),但未能建立规则。 请帮忙!
答案 0 :(得分:1)
如果最后一个值始终由'\t'
分隔,则可以使用以下方法:
s = '18.0 8 307.0 130.0 3504. 12.0 70 1\t"chevrolet chevelle malibu"'
lst = [*s.split('\t')[0].split(), s.split('\t')[-1]]
print(lst)
打印:
['18.0', '8', '307.0', '130.0', '3504.', '12.0', '70', '1', '"chevrolet chevelle malibu"']
答案 1 :(得分:1)
可以通过以下代码实现:
>>> string = '18.0 8 307.0 130.0 3504. 12.0 70 1\t"chevrolet chevelle malibu"'
>>> [y for (i, x) in enumerate(string.split('"')) for y in ([y.strip() for y in x.split()] if i % 2 == 0 else [x])]
['18.0', '8', '307.0', '130.0', '3504.', '12.0', '70', '1', 'chevrolet chevelle malibu']