Python Glossary Русский

all Python 3Data typesterm

bytes

bytes

An immutable sequence of bytes (integers 0–255). Used for binary data and for text in a particular encoding.

Syntax

bytes(n)  bytes(iterable)  b"..."  bytes.fromhex(hex_str)  bytes(source, encoding)

bytes(5) is not the digits of 5 but five zero bytes b'\x00\x00\x00\x00\x00' — a common trap. Indexing yields an int (b[0] → 65) while slicing yields bytes again, and the contents are immutable — reach for its mutable twin bytearray when you need to change them.

Examples

print(bytes(5))              # → b'\x00\x00\x00\x00\x00'
print(b"hello")              # → b'hello'
print(bytes([72, 101, 108]))  # → b'Hel'
print(bytes.fromhex("ff00ab"))  # → b'\xff\x00\xab'
b = b"ABC"; print(b[0])      # → 65
print(b"hello".hex())         # → 68656c6c6f
print(bytes("hello", "utf-8"))  # → b'hello' (из строки с кодировкой)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy