I want to remove elements of a bytes
parameter in a function. I want the parameter to be changed, not return a new object.
def f(b: bytes):
b.pop(0) # does not work on bytes
del b[0] # deleting not supported by _bytes_
b = b[1:] # creates a copy of b and saves it as a local variable
io.BytesIO(b).read(1) # same as b[1:]
What's the solution here?
Just use a bytearray
:
>>> a = bytearray(b'abcdef')
>>> del a[1]
>>> a
bytearray(b'acdef')
It's almost like bytes
but mutable:
The
bytearray
class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that thebytes
type has, see Bytes and Bytearray Operations.
Using a bytearray as shown by @MSeifert above, you can extract the first n elements using slicing
>>> a = bytearray(b'abcdef')
>>> a[:3]
bytearray(b'abc')
>>> a = a[3:]
a
bytearray(b'def')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With