First of all passing an integer(say n
) to bytes()
simply returns an bytes string of n
length with null bytes. So, that's not what you want here:
Either you can do:
>>> bytes([5]) #This will work only for range 0-256.
b'\x05'
Or:
>>> bytes(chr(5), 'ascii')
b'\x05'
As @simonzack already mentioned, bytes are immutable, so to update (or better say re-assign) its value, you need to use the +=
operator.
>>> s = b'\x01\x02\x03'
>>> s += bytes([5]) #or s = s + bytes([5])
>>> s
b'\x01\x02\x03\x05'
>>> s = b'\x01\x02\x03'
>>> s += bytes(chr(5), 'ascii') ##or s = s + bytes(chr(5), 'ascii')
>>> s
b'\x01\x02\x03\x05'
Help on bytes()
:
>>> print(bytes.__doc__)
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
Or go for the mutable bytearray
if you need a mutable object and you're only concerned with the integers in range 0-256.