chr() equivalent returning a bytes object, in py3k chr() equivalent returning a bytes object, in py3k python-3.x python-3.x

chr() equivalent returning a bytes object, in py3k


Try the following:

b = bytes([x])

For example:

>>> bytes([255])b'\xff'


Consider using bytearray((255,)) which works the same in Python2 and Python3. In both Python generations the resulting bytearray-object can be converted to a bytes(obj) which is an alias for a str() in Python2 and real bytes() in Python3.

# Python2>>> x = bytearray((32,33))>>> xbytearray(b' !')>>> bytes(x)' !'# Python3>>> x = bytearray((32,33))>>> xbytearray(b' !')>>> bytes(x)b' !'


In case you want to write Python 2/3 compatible code, use six.int2byte