[Python-ideas] a new bytestring type?
Stephen J. Turnbull
stephen at xemacs.org
Mon Jan 6 18:14:07 CET 2014
Geert Jansen writes:
> One use case I came across was when creating chunks for the HTTP
> chunked encoding. Chunks contain a ascii header, a raw/encoded chunk
> body, and an ascii trailer. Using a bytes.format, it would look like
> this:
>
> chunk = '{0:X}\r\n{1}\r\n'.format(len(buf), buf)
You forgot the b prefix.
> This is what I am using now:
>
> chunk = bytearray()
> chunk.extend('{0:X}\r\n'.format(len(buf)).encode('ascii'))
> chunk.extend(buf)
> chunk.extend('\r\n'.encode('ascii'))
Either of those is a big win compared to this?
# OK, we'd want efficient definition of a bunch of these,
# which is a cost.
def itox (n):
return '{0:X}'.format(n).encode('ascii')
chunk = b'\r\n'.join([itox(len(buf)), buf, b''])
But see my response to Andrew, also.
More information about the Python-ideas
mailing list