Why does "bytes(n)" create a length n byte string instead of converting n to a binary representation?
python, python-3.x
Solution
Python 3.5+ introduces %-interpolation (`printf`-style formatting) for bytes:
>>> b'%d\r\n' % 3
b'3\r\n'
See PEP 0461 -- Adding % formatting to bytes and bytearray.
On earlier versions, you could use `str` and `.encode('ascii')` the result:
>>> s = '%d\r\n' % 3
>>> s.encode('ascii')
b'3\r\n'
Note: It is different from what `int.to_bytes` produces:
>>> n = 3
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x03'
>>> b'3' == b'\x33' != b'\x03'
True
Problem
I was trying to build this bytes object in Python 3: `b'3\r\n'` so I tried the obvious (for me), and found a weird behaviour: ``` >>> bytes(3) + b'\r\n' b'\x00\x00\x00\r\n' ``` Apparently: ``` >>> bytes(10) b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ``` I've been unable to see any pointers on why the bytes conversion works this way reading the documentation. However, I did find some surprise messages in this Python issue about adding `format` to bytes (see also Python 3 bytes formatting): http://bugs.python.org/issue3982 This interacts even more poorly with oddities like bytes(int) returning zeroes now and: It would be much more convenient for me if bytes(int) returned the ASCIIfication of that int; but honestly, even an error would be better than this behavior. (If I wanted this behavior - which I never have - I'd rather it be a classmethod, invoked like "bytes.zeroes(n)".) Can someone explain me where this behaviour comes from?