Binary data handling ?

Peter Abel p-abel at t-online.de
Thu Aug 28 18:50:16 CEST 2003


"Bill Loren" <lorenb2 at bezeqint.net> wrote in message news:<mailman.1062079383.31727.python-list at python.org>...
> Hello ppl,
> 
> I'm having difficulties to accomplish some simple chores with binary data.
> I'm having a string (?) which I received via an HTTP transactions which is a
> binary file.
> Problem is the webserver I'm communicating with injected a \x0D before every
> \x0A,
> and I need to remove those 0x0D characters from my buffer before saving it
> to disk.
> 
> any ideas ?
> 
> I tried the following without any success:
> string.replace("%c%c" % (13,10), "%c" % (10))
> string.replace("\x0d\x0a", "\0x0a")
> 
> thx
> ~B

>>> # A short function to generate a string with 0x0D's
>>> def make_bin():
... 	bytes=[]
... 	for i in range(20):
... 		bytes.append(chr(i))
... 		# every 5th char is a 0x0D
... 		if not i%5:
... 			bytes.append(chr(0x0D))
... 	return ''.join(bytes)
... 
>>> binary=make_bin()
>>> binary
'\x00\r\x01\x02\x03\x04\x05\r\x06\x07\x08\t\n\r\x0b\x0c\r\x0e\x0f\r\x10\x11\x12\x13'
>>> # split the string at the 0x0D's and join it again
>>> binary_without_x0D=''.join(binary.split(chr(0x0D)))
>>> #et voila
>>> binary_without_x0D
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0e\x0f\x10\x11\x12\x13'
>>> 

Regards
Peter




More information about the Python-list mailing list