Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a range of bytes from a bytes object in python?

I am pretty new to python and sometimes things that seems pretty easy become lot complicated than expected

I am currently using a bytes buffer to read from a socket:

data = self.socket.recv(size)

and then process part of that buffer and need remove it

The thing is that I've been looking for a way to do that and didn't find a clue in the whole evening, I am pretty sure that I am not getting any fair results because of the words involved, or maybe it's not possible

I tried with "del" but got an error saying that it's not supported

Am I doing it the wrong way? Maybe someone could lead me the right way? :)

like image 683
Jade Avatar asked Sep 01 '13 21:09

Jade


2 Answers

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.

like image 150
Steve Jessop Avatar answered Nov 15 '22 12:11

Steve Jessop


I think I found the proper way, just looking from another perspective:

self.data = self.data[Index:]

just copying what I need to itself again

like image 4
Jade Avatar answered Nov 15 '22 14:11

Jade