Skip to main content
The bytes type in Python is an immutable sequence of integers in the range 0 <= x < 256. It is the fundamental built-in data structure for representing raw binary data, contrasting directly with the str type, which represents sequences of Unicode characters.

Instantiation and Syntax

Byte Literals Prefixing a string literal with b or B creates a bytes object. Only ASCII characters are permitted within byte literals. Bytes with numeric values of 128 or greater must be expressed using hexadecimal, octal, or other escape sequences.
The bytes() Constructor The constructor instantiates bytes objects from iterables of integers (where 0 <= x < 256), integers, strings (which strictly require an encoding argument), or objects implementing the buffer protocol.
Encoding Strings Converting a Unicode str to bytes can also be achieved using the string’s encode() method. In Python 3, this method defaults to the UTF-8 encoding scheme and can be called without arguments, though alternative encodings can be explicitly provided.

Core Characteristics

Immutability Like str and tuple, bytes objects are immutable. They cannot be modified in place. Any operation that alters the data will allocate and return a new bytes object in memory. Indexing and Slicing Because bytes are fundamentally sequences of integers, indexing a single position evaluates to an int. Conversely, slicing a bytes object evaluates to a new bytes object.
Method Parity with str The bytes class implements a nearly identical API to the str class, including methods like split(), find(), replace(), and upper(). However, passing a str to these methods will raise a TypeError. The argument requirements depend strictly on the method:
  • Methods like split() can be called without arguments to split on ASCII whitespace. If a delimiter is provided to split() or a substring to replace(), it must be a bytes-like object. Passing an integer or string will raise a TypeError.
  • Methods like find() and count() accept either bytes-like objects or an integer representing a single byte value (0 <= x < 256).
  • Methods like upper() and lower() take no arguments and operate directly on the underlying byte values.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More