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

I have this code for formatting received data from serial port into 2 variables it receives 'v=220f=50'

and formats 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 instead I get voltage = 505048

and freq = 5348

!, I tried translating them to int()

but nothing changed. maybe it's some kind of encoding.

ps: I want to save them to a file, so no need to cast them to integers:

fw.write('Voltage is: {0};\t  Frequency is: {1}\n'.format(voltage, freq))

      

+3


source to share


1 answer


You have a bytes object from ser.readline()

. First you have to 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 also suggest that you parse the values ​​using regex. The current approach breaks easily when the length of any of the values ​​changes.

+3


source







All Articles