How to append to bytes in python 3

PythonPython 3.x

Python Problem Overview


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'

Python Solutions


Solution 1 - Python

bytes is immutable. Use bytearray.

xs = bytearray(b'\x01\x02\x03')
xs.append(5)

Solution 2 - Python

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 that bytes are immutable, so to update(or better say re-assign it to a new string) 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfelixbadeView Question on Stackoverflow
Solution 1 - PythonsimonzackView Answer on Stackoverflow
Solution 2 - PythonAshwini ChaudharyView Answer on Stackoverflow