python ValueError:float()的无效文字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21943877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python ValueError: invalid literal for float()
提问by astronomerdave
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)
Sometimes, the script fails on the line which converts the values to float:
有时,脚本在将值转换为浮点数的行上失败:
File "./projector.py", line 129, in get_temp
data[ch] = float(temp)
ValueError: invalid literal for float(): +135.057E+0
+078.260E+0
+00029
文件“./projector.py”,第 129 行,在 get_temp
数据[ch] = float(temp)
ValueError:float() 的无效文字:+135.057E+0
+078.260E+0
+00029
but this is NOT an invalid literal. If I enter this into any python shell,
但这不是无效的文字。如果我将其输入任何 python shell,
float(+135.057E+0)
then it correctly returns 135.057.
然后它正确返回 135.057。
So what is the problem?
那么问题是什么?
采纳答案by g.d.d.c
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:
我几乎可以保证问题是某种非打印字符存在于您从套接字中拉出的值中。看起来您使用的是 Python 2.x,在这种情况下,您可以使用以下命令检查它们:
print repr(temp)
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.
您可能会在其中看到以 形式转义的内容\x00。当您直接打印到控制台时,这些非打印字符不会出现,但它们的存在足以对将字符串值解析为浮点数产生负面影响。
-- Edited for question changes --
-- 针对问题更改进行了编辑 --
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.
为了转换每个值,但如果您的函数应该返回单个浮点值,这可能会导致混淆。无论如何,问题肯定围绕着您不希望在从套接字检索到的值中看到的字符的存在。
回答by parovelb
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
我在从数字秤读取串行输出时遇到了类似的问题。我正在从 18 个字符长的输出字符串中读取 [3:12]。
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
在我的情况下,有时会有一个空字符“\x00”(NUL),它神奇地出现在秤的回复字符串中并且没有打印出来。
I was getting the error:
我收到错误:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
经过一番研究,我写了几行代码,适用于我的情况。
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
这些帖子中的答案有帮助:
回答by mrk
Watch out for possible unintended literals in your argument
注意你的论点中可能出现的意外文字
for example you can have a space within your argument, rendering it to a string / literal:
例如,您可以在参数中有一个空格,将其呈现为字符串/文字:
float(' 0.33')
After making sure the unintended space did not make it into the argument, I was left with:
在确保意外的空间没有进入争论之后,我得到了:
float(0.33)
Like this it works like a charm.
像这样它就像一个魅力。
Take away is:Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.
需要注意的是:注意输入中意外的文字(例如,您没有看到的空格)。

