要浮动的Python字符串

时间:2016-07-13 19:19:09

标签: python python-2.7

我试图从文本文件中的一行中提取浮点数,但我不能理解如何将行中的数字(str)转换为浮点数

for line in fh:
    if not line.startswith("A specific string") : continue
    count = count + 1
#linevalue gets the numbers in the line that i'm interested in, so in order 
#to have only the numeric value i tried getting rid of the other text in the line by only
# selecting that range (20:26
    linevalue = line[20:26]
    float(linevalue)
    print type(linevalue)
    print linevalue

使用float(linevalue)的尝试转换没有通过,程序的输出仍然是:

<type 'str'> 0.4323

任何人都可以帮助我理解我错过了什么吗?

非常感谢你的时间。

1 个答案:

答案 0 :(得分:3)

我想你想要:

linevalue = float(linevalue)

您正确地将字符串值转换为浮点值,但您没有将该值保存在任何位置。 (调用float不会修改现有变量;它会返回一个新值。)

相关问题