Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python ValueError: invalid literal for float()

Tags:

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

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

float(+135.057E+0)

then it correctly returns 135.057.

So what is the problem?

like image 422
astronomerdave Avatar asked Feb 21 '14 19:02

astronomerdave


People also ask

How do I fix this ValueError invalid literal for int with base 10 error in Python?

You can solve this error by using Python isdigit() method to check whether the value is number or not. The returns True if all the characters are digits, otherwise False .

What is an invalid literal in Python?

Conclusion. ValueError: invalid literal for int() with base 10 occurs when you convert the string or decimal or characters values not formatted as an integer. To solve the error, you can use the float() method to convert entered decimal input and then use the int() method to convert your number to an integer.


1 Answers

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.

like image 178
g.d.d.c Avatar answered Oct 15 '22 16:10

g.d.d.c