68

I have some bytes.

b'\x01\x02\x03'

And an int in range 0..255.

5

Now I want to append the int to the bytes like this:

b'\x01\x02\x03\x05'

How to do it? There is no append method in bytes. I don't even know how to make the integer become a single byte.

>>> bytes(5)
b'\x00\x00\x00\x00\x00'
felixbade
  • 1,009
  • 3
  • 10
  • 18

2 Answers2

81

bytes is immutable. Use bytearray.

xs = bytearray(b'\x01\x02\x03')
xs.append(5)
simonzack
  • 19,729
  • 13
  • 73
  • 118
27

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Both solutions can be optimized by using `bytes((5,))` instead of the first one and `(5).to_bytes(1, "little")` for the second one. `int.to_bytes()` can be used to get longer byte sequences in the specified order from an integer of arbitrary size. – Bachsau Dec 14 '18 at 03:15
  • 3
    FWIW, a byte is 0..255, not 0..256 – Russ Schultz Oct 21 '20 at 18:22
  • +1 for mentioning the += operator, i dont know why .append() only works on integers and doesn't take a bytes or another bytearray object, how infuriating – mgrandi Jan 25 '21 at 08:19
  • @mgrandi use .extend() and not += – toppk Jul 06 '23 at 03:26