[issue3982] support .format for bytes

Terry J. Reedy report at bugs.python.org
Mon Mar 7 20:09:20 CET 2011


Terry J. Reedy <tjreedy at udel.edu> added the comment:

You are right, I misinterpreted the meaning of 's' without a count (and opened #11436 to clarify). However, for the fairly common case where a variable-length binary block is preceded by a 4 byte *binary* count, one can do something which is not too bad:

>>> block = b'lsfjdlksaj'
>>> n=len(block)
>>> struct.pack('I%ds'%n, n, block)
b'\n\x00\x00\x00lsfjdlksaj'

If leading blanks are acceptable for your example with count as ascii hex digits, one can do something that I admit is worse:

>>> struct.pack('10s%ds2s'%n, ('%8x\r\n'%n).encode(), block, b'\r\n')
b'       a\r\nlsfjdlksaj\r\n'

Of course, for either of these in isolation, I would probably only use .pack for the binary conversion and otherwise use '+' or b''.join(...).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue3982>
_______________________________________


More information about the Python-bugs-list mailing list