Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python .format(*str) returns 5348 instead of 50

I have this code to format the received data from Serial port to 2 variables it receives 'v=220f=50' and format it to

 reads = ser.readline()                # data received is 'v=220f=50'         
 voltage = int('{2}{3}{4}'.format(*reads))
 freq = '{7}{8}'.format(*reads)

so voltage = 220 and freq = 50 but i get voltage = 505048 and freq = 5348 instead!, I tried casting them to int() but nothing changed. maybe it's some sort of encoding.

ps: I want to store them into a file so no need to cast them to integers:

fw.write('Voltage is: {0};\t  Frequency is: {1}\n'.format(voltage, freq))
like image 573
Abdulrahman AZ Avatar asked Feb 22 '26 16:02

Abdulrahman AZ


1 Answers

You have a bytes object from ser.readline(). You should first convert to string with .decode:

>>> reads = b'v=220f=50'
>>> voltage = int('{2}{3}{4}'.format(*reads))
>>> voltage
505048
>>> voltage = int('{2}{3}{4}'.format(*reads.decode()))
>>> voltage
220

I would also suggest you look into parsing the values using regex. The current approach would easily break when the length of any of the values change.

like image 72
Moses Koledoye Avatar answered Feb 24 '26 06:02

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!