Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Strange Code
#1
I am new to python, but not to coding. I have been coding in C, C++, php and some others but just started coding in python. I have come across a piece of code that I don't understand and can't find any references in the documentation (probably because I don't know where to look in the documentation). Here is the code:
decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))

The piece I don't understand is the (ser_bytes[0:len(ser_bytes)-2].decode("utf-8") where ser_bytes is previously defined by
ser_bytes = ser.readline(). I get the len() and decode() functions, but the [0:...] has me baffled. Can someone tell me what this might be? Some kind of array?
Thanks.
Reply
#2
ser_bytes[0:len(ser_bytes)-2] part is Python's slicing mechanism for lists, strings, or byte-like objects.
To give a example,code look like reading from a serial connection
>>> ser_bytes = b'123.45\r\n'
>>> # Slice the byte sequence to remove the last two characters (\r and \n)
>>> sliced_bytes = ser_bytes[0:len(ser_bytes)-2]
>>> sliced_bytes
b'123.45'
>>> # Ar this point can just convert to float,no decode needed
>>> float_value = float(sliced_bytes)
>>> float_value
123.45
>>> type(float_value)
<class 'float'>
Gribouillis likes this post
Reply
#3
And there is no need for the len() function. These are equivalent:
ser_bytes[0:len(ser_bytes)-2]
ser_bytes[0:-2]
ser_bytes[:-2]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple Code - Strange Results? emerger 5 4,469 Jan-28-2018, 05:00 AM
Last Post: ka06059

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020