Just call the bytes
constructor.
As the docs say:
… constructor arguments are interpreted as for
bytearray()
.
And if you follow that link:
If it is an iterable, it must be an iterable of integers in the range
0 <= x < 256
, which are used as the initial contents of the array.
So:
>>> list_of_values = [55, 33, 22]
>>> bytes_of_values = bytes(list_of_values)
>>> bytes_of_values
b'7!\x16'
>>> bytes_of_values == b'\x37\x21\x16'
True
Of course the values aren’t going to be \x55\x33\x22
, because \x
means hexadecimal, and the decimal values 55, 33, 22
are the hexadecimal values 37, 21, 16
. But if you had the hexadecimal values 55, 33, 22
, you’d get exactly the output you want:
>>> list_of_values = [0x55, 0x33, 0x22]
>>> bytes_of_values = bytes(list_of_values)
>>> bytes_of_values == b'\x55\x33\x22'
True
>>> bytes_of_values
b'U3"'