bytes doesn't support item deletion because it's immutable. To "modify" strings and string-like objects you need to take a copy, so to remove olddata[start:end] do:

newdata = olddata[:start] + olddata[end:]

Of course that's a fair amount of copying, not all of which is necessary, so you might prefer to rework your code a bit for performance. You could use bytearray (which is mutable). Or perhaps you could find a way to work through the buffer (using an index or iterating over its elements), instead of needing to shorten it after each step.

Answer from Steve Jessop on Stack Overflow
Top answer
1 of 2
3

Use bytes.replace to replace the substring with an empty string:

b = b'Today, in the digital age, any type of data, such as text, images, and audio, can be\r\ndigitized, stored indefinitely, and transmitted at high speeds. Notwithstanding these\r\nadvantages, digital data also have a downside. They are easy to access illegally, tamper\r\nwith, and copy for purposes of copyright violation.\r\nThere is therefore a need to hide secret identification inside certain types of digital\r\ndata. This information can be used to prove copyright ownership, to identify attempts\r\nto tamper with sensitive data, and to embed annotations. Storing, hiding, or embedding\r\nsecret information in all types of digital data is one of the tasks of the field of\r\nsteganography.\r\nSteganography is the art and science of data hiding. In contrast with cryptography,\r\nwhich secures data by transforming it into another, unreadable format, steganography\r\nmakes data invisible by hiding (or embedding) them in another piece of data, known\r\nalternatively as the cover, the host, or the carrier. The modified cover, including the\r\nhidden data, is referred to as a stego object. It can be stored or transmitted as a message.\r\nWe can think of cryptography as overt secret writing and of steganography as covert\r\nsecret writing.\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

b = b.replace(b'\x00', b'')
assert b.endswith(b'writing.')
2 of 2
2

Bytes objects behave like many other iterables, which means slicing and indexing should work as expected. Since the character you want to remove is specifically at the end and the object supports the method, the solution is the same as in striping characters from the end of a string. Just make sure to pass the desired characters are bytes.

>>> my_bytes = b'blah\x00\x00\x00'
>>> my_bytes.rstrip(b'\x00')
b'blah'
Find elsewhere
🌐
Python.org
discuss.python.org › python help
Strip byte string and take only importante values - Python Help - Discussions on Python.org
July 7, 2023 - Hello all…good day…please help on how to strip byte string as below: input : b'\x081F304984\x0843501' output : 1F304984 thanks a lot