Sanity
Sanity

Reputation: 13

String to int/float conversion not working in python on raspberry pi

I am trying to send values from a esp32 on my network to my RPi via mqtt, which then evaluates these values and does some stuff with it.

I've written the code and tried it on my pc without any problems, but when executing the exact same code on the RPi it starts spitting out ValueErrors.

payload = str(message.payload)
payload = float(payload[2:-1])

When running the code like this, it says:

ValueError: could not convert string to float:

Trying to convert it to an integer first also returns an error:

ValueError: invalid literal for int() with base 10: ''

(The [2:-1] is needed because the payload/string that is to be converted is always received as b'payload')

It doesn't throw out any errors when used on the pc. I have also tried printing out the strings before converting them, which showed that they only consist of numbers.

Im running Python3.4 on both my pc and the RPi (tried 2.7 as well, didn't work.)

I hope anyone can explain this weird behaviour to me, thanks in advance.

Upvotes: 0

Views: 1567

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

  1. Slicing is not the correct way to convert a bytes array to str.

  2. string[2:-1] returns an empty string for any string shorter than 3 characters.

As a matter of fact, both int and float accept bytes arrays that represent numbers, so you shouldn't even bother.

float(message.payload) should work (in case it's not empty and represents a number of course).

Upvotes: 1

Related Questions