如何在Python中从字符串中提取Double?

问题描述 投票:1回答:3

目前,我有这个功能,但它仅适用于整数(整数),不能用于双精度:

S = "Weight is 3.5 KG"
weight = [int(i) for i in S.split() if i.isdigit()] 

print(weight)

结果:[]

python printing double
3个回答
0
投票

您可以使用re

print(re.findall('\d+\.\d+',S)
#['3.5']

使用try-except

for i in S.split():
    try:
        if float(i):
            new.append(i)
    except Exception:
        pass

print(new)
#['3.5']

0
投票

您可以使用正则表达式提取浮点数:

import re

S = "Weight is 3.5 KG"
pattern = re.compile(r'\d+\.\d+')

weights = list(map(float, re.findall(pattern, S)))
print(weights)

re.findall()将返回您在文本中找到的数字列表。map函数会将列表结果转换为浮点数。由于它返回一个生成器,因此您需要将其转换为list


0
投票

以下代码将完成您放置的示例的工作:

if __name__ == "__main__":

    S = "Weight is 3.5 KG"

    # split the string
    S_split = S.split()

    for x in S_split:
        if '.' in x:
            print(float(x))

输出:

3.5
© www.soinside.com 2019 - 2024. All rights reserved.