如何用逗号分隔一些数字从字符串中提取一些数字?

时间:2015-04-04 06:02:52

标签: python regex string numbers comma

让我们说一个字符串

"1977   1,048.20    1,039.40    894.10  694.70  664.20  1,031.60    928.60  18.80   10:27:05    "

如何提取数字,即

1977    1048.20 1039.40 894.10  694.70  664.20  1031.60 928.60  18.80   10 27 05

如果此字符串没有逗号分隔,我可以提取数字 数字。但不知道如何在上述情况下获取它们。

下面是我的代码,其中没有逗号的情况,对于带逗号的情况不起作用。

temperaturetime=re.findall(r'\d*\.?\d+',line)

2 个答案:

答案 0 :(得分:1)

请尝试以下代码:

x = "1977   1,048.20    1,039.40    894.10  694.70  664.20  1,031.60    928.60  18.80   10:27:05    "
nums = [float(item) if '.' in item else int(item) for item in x.replace(':', ' ').replace(',', '').split()]
print nums #[1977, 1048.2, 1039.4000000000001, 894.10000000000002, 694.70000000000005, 664.20000000000005, 1031.5999999999999, 928.60000000000002, 18.800000000000001, 10, 27, 5]

答案 1 :(得分:1)

如果你想保留逗号,那么.split()就能正常工作。

c = "1977   1,048.20    1,039.40    894.10  694.70  664.20  1,031.60    928.60  18.80   10:27:05    "
print c.split()['1977', '1,048.20', '1,039.40', '894.10', '694.70', '664.20', '1,031.60', '928.60', '18.80', '10:27:05']

如果你想删除逗号,

with_comma = c.split()
without_comma = [x.replace(',','') for x in with_comma]
print without_comma
['1977', '1048.20', '1039.40', '894.10', '694.70', '664.20', '1031.60', '928.60', '18.80', '10:27:05']

似乎您输入的最后一个条目格式不同,您必须处理它而不是将列表转换为[float(x)for x in list]