Search code examples
pythonbinary-data

How to strip first and last byte from binary data in Python


I have a Python program that is receiving data from a UDP socket. Python is reading it as binary data.

Each datagram should start with the STX character (0x02) and end with the ETX character (0x03). I want my code to test the first and last character and, if they are correct, to strip them before passing the rest of the data out of my function to be further processed by the calling function.

I believe I can test the first character with data[0].

How can I get the length of the data so as to test the last character?

How can I get a "substring" of the data?

I am tempted to decode it to a string, but suspect that involves extra overhead and anyway, as a Python novice, I have no idea how.


Solution

  • As I understand the question you need to slice your data.
    So you can slice from 2nd character by using data[1:] and up to last character but not including by using data[:-1].
    As a combination of both, you can use

    data[1:-1]
    

    You can get length by using len() function.

    len(data)
    

    You can get the last byte by:

    data[-1]