无法使用float转换字符串 - Python 3

时间:2017-03-03 01:56:18

标签: python string python-3.x floating-point

我很确定解决方案很简单但不知何故通常的浮动无法正常工作。

output = open('output.txt', 'wt')
with open('input.txt', 'r') as file:
    file = file.readlines()
    for x in range(0,len(file)):
        if file[x][0:6] == 'NUMBER':
            print(file[x][11:18]) 
            float(file[x][11:18])

打印会给我' 11111' , 但是float给了我错误ValueError:无法将字符串转换为float: 这里发生了什么。我需要它作为浮点数进行一些数学运算。

更新。我猜它是因为我试图转换一个空的空间。第一行导致此错误。浮动('')会出错。

NUMBER
*
NUMBER 111111111111111111111

1 个答案:

答案 0 :(得分:2)

@Bijoy在评论中提出的想法的一个版本:如果问题是'NUMBER'后面的字符串有时是空的,并且这种情况应该总是映射到浮点0.0,你可以使用错误捕获来编写float()的特殊用途版本:

def getfloat(s):
    try:
        return float(s)
    except ValueError:
        return 0.0

这适用于您的情况,但有反直觉的行为,例如: getfloat("hello world") == 0.0