python ValueError: invalid literal for float()

后端 未结 3 1981
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 04:23

I\'ve a script which reads temperature data:

def get_temp(socket, channels):

    data = {}
    for ch in channels:
        socket.sendall(\'KRDG? %s\\n\' %          


        
3条回答
  •  悲哀的现实
    2020-12-06 04:59

    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)
    

    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.

    -- 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.

提交回复
热议问题