python ValueError:无效的文字float() [英] python ValueError: invalid literal for float()

查看:123
本文介绍了python ValueError:无效的文字float()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个读取温度数据的脚本:

I've a script which reads temperature data:

def get_temp(socket, channels):

    data = {}
    for ch in channels:
        socket.sendall('KRDG? %s\n' % ch)
        time.sleep(0.2)
        temp = socket.recv(32).rstrip('\r\n')

        data[ch] = float(temp)

有时,脚本在将值转换为float的行上失败:

Sometimes, the script fails on the line which converts the values to float:

文件"./projector.py",第129行,位于get_temp
数据[ch] = float(temp)
ValueError:无效的float()文字:+ 135.057E + 0
+ 078.260E + 0
+00029

File "./projector.py", line 129, in get_temp
data[ch] = float(temp)
ValueError: invalid literal for float(): +135.057E+0
+078.260E+0
+00029

但这不是无效的文字.如果我将其输入任何python shell中,

but this is NOT an invalid literal. If I enter this into any python shell,

float(+135.057E+0)

然后正确返回135.057.

then it correctly returns 135.057.

那是什么问题?

推荐答案

我几乎会保证问题是拔出套接字的值中存在某种非打印字符.看来您使用的是Python 2.x,在这种情况下,您可以使用以下命令进行检查:

I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:

print repr(temp)

您可能会在其中看到以\x00格式转义的内容.当您直接在控制台上打印时,这些非打印字符不会显示,但是它们的存在足以对将字符串值解析为浮点数产生负面影响.

You'll likely see something in there that's escaped in the form \x00. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.

-编辑问题更改-

这对于您的问题来说部分准确,但是,根本原因似乎是您正在从套接字读取比预期更多的信息,或者接收到多个值.您可以做类似

It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like

map(float, temp.strip().split('\r\n'))

为了转换每个值,但是如果您的函数应该返回单个浮点值,则可能会引起混淆.无论如何,问题肯定与您从套接字检索到的值中没有出现您希望看到的字符有关.

In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.

这篇关于python ValueError:无效的文字float()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆