Python将String的一部分转换为Float

时间:2017-10-23 10:38:10

标签: python python-3.x

我正在尝试制作一个包含2个字符串的列表:

List=["Hight = 7.2", "baselength = 8.32"]

但我在尝试从字符串中提取数字时遇到问题:

例如:

如果"Hight = 7.2",则结果应为:7.2

或如果"Hight= 7.3232"则结果应为:7.3232

5 个答案:

答案 0 :(得分:2)

使用re.findall

>>> out = []
>>> for s in l: 
        out.append( float(re.findall('\d+(?:\.\d+)?', s)[0]) ) 

>>> out
=> [7.2, 8.0]

或者,没有regex,使用split

>>> out = []
>>> for s in l:
        num = s.replace(' ','').split('=')[1]    
        #note : removed whitespace so don't have to deal with cases like
        #        `n = 2` or `n=2`
        out.append(float(num)) 

>>> out
=> [7.2, 8.0]

#driver values:

IN : l = ["Hight = 7.2","baselength = 8"]

答案 1 :(得分:0)

这个怎么样

[(item.split('=')[0],float(item.split('=')[1]) ) for item in List]

输出:

[('Hight ', 7.2), ('baselength ', 8.32)]

答案 2 :(得分:0)

具有与值关联的标签最好使用字典进行管理,但是如果必须将每个label = value对作为列表中的条目,因为可能是从其他地方将其读入Python,则可以使用{{ 1}}模块从列表中的每个字符串中提取数值:

re

答案 3 :(得分:0)

您可以使用理解 列表转换为字典:

import re

List=["Height = 7.2", "baselength = 8.32"]

rx = re.compile(r'(?P<key>\w+)\s*=\s*(?P<value>\d+(?:\.\d+)?)')

Dict = {m.group('key'): float(m.group('value')) 
        for item in List
        for m in [rx.search(item)]}

print(Dict)
# {'Height': 7.2, 'baselength': 8.32}

之后,您可以使用以下方式访问您的值Dict["Height"](此处:7.2)。

答案 4 :(得分:0)

这很简单。将此方法用于任何类型的值

List=["Hight = 7.2", "baselength = 8.32"]
# showing example for one value , but you can loop the entire list 
a = List[0].split("= ")[1] #accessing first element and split with "= "
print a
'7.2'
相关问题