all Python 3Strings (str)term
b"..." byte strings
bytes
Byte strings (b"...") hold a sequence of bytes rather than Unicode characters. Each item is an integer 0–255. Used when working with binary data.
Syntax
b"строка" b'строка'
Indexing and slicing disagree on purpose: b[0] gives the integer 104, while b[0:1] gives back a bytes object, b'h'. Bytes never mix with str — b'a' + 'b' raises TypeError, and crossing between them goes through .encode() and .decode() with an encoding you have consciously chosen. Like str, bytes is immutable; when you need to patch bytes in place, reach for bytearray.
Examples
b = b"hello"; print(type(b)) # → <class 'bytes'>
print(b[0]) # → 104
print(b"hello" + b" world") # → b'hello world'
print(b"hi" * 3) # → b'hihihi'
print(b"hello".decode("utf-8")) # → hello
print("hello".encode("utf-8")) # → b'hello'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy