Binary data
Representing network packets, file contents, or serialized payloads without accidental mutation.
Python · Class
bytes is Python’s immutable binary sequence type. It stores individual byte values as integers from 0 through 255 and can be created from literals, iterable data, or encoded text.
bytes creates an immutable binary sequence whose elements are integers from 0 through 255. Use a bytes literal or construct it from an iterable of integers, an existing bytes-like source, or text together with an encoding and optional error policy; convert it back to text with decode().
bytes(source=b'')
bytes(source, encoding, errors='strict')| Name | Type | Description |
|---|---|---|
source | object | Source value, defaulting to empty bytes; it may provide the initial byte sequence. |
encoding | str | Text encoding used when source is a string. |
errors | str | Policy for encoding errors, defaulting to strict. |
A new immutable bytes object containing values in the range 0 through 255.
bytes provides the non-mutating counterpart to bytearray; choose bytearray when in-place changes are required.bytearray(), including an optional encoding and error policy for text.b-prefixed literal instead of calling the constructor.bytes useful for wire formats and encoded payloads.ValueError.bytes object; use slicing when a bytes result is needed.payload = "café".encode("utf-8")
print(payload)
print(payload.decode("utf-8"))
print(payload[0])The string is encoded into immutable bytes, then decoded back to text; indexing returns the integer value of one byte.
Representing network packets, file contents, or serialized payloads without accidental mutation.
Turning Unicode text into a protocol or storage representation with an explicit character encoding.
Reading protocol fields whose values are ASCII-compatible byte sequences.
bytes object represent?bytes is an immutable sequence of integers, with each integer constrained to 0 through 255. It is suited to binary data and supports sequence operations such as indexing and slicing.
Follow-up: How would you obtain text from it? Call decode() with the encoding used for the original text; the chosen error policy can also affect handling of invalid data.
Use bytes(text, encoding, errors) or text.encode(encoding, errors) when starting from text. The encoding is required for text conversion, while the error handling argument defaults to strict behavior.
Follow-up: Why can bytes(text) not be used directly? A text object needs an explicit encoding to define how its characters become binary values.
A bytes literal uses a b prefix, such as b'abc', and supports string-like quoting forms. Direct literal characters must be ASCII; other byte values require escape sequences.
Follow-up: How can hexadecimal input be handled? Use the fromhex() class method to create bytes from a hexadecimal string.
bytearraymemoryviewbytes literalsBytes and Bytearray Operationsdecode()fromhex()