ruk·si

🐍 Python
Byte Objects

Updated at 2018-06-09 17:43

Bytes objects are immutable sequences of integers between 0 and 255. Byte literals have their own syntax that starts with b''.

arr: bytes = bytes((255, 0, 100, 200))
assert arr == b'\xff\x00d\xc8'

Byte array objects are mutable bytes objects.

arr: bytearray = bytearray((0, 1, 2, 3))
assert arr == b'\x00\x01\x02\x03'

arr[3] = 23
assert arr == b'\x00\x01\x02\x17'

Some standard library features will behave differently when given bytes instead of strings.

  • Regular expressions: rb'' will only match ASCII characters, r'' also matches Unicode.
  • os module functions work with kernel stuff and usually only support bytes. Conversion from strings to bytes is automatic.

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho