bytes()
Creates a bytes object, an unchangeable sequence of numbers from 0 to 255, used for files, network data and encoded text.
bytes()
bytes(source)
bytes(source, encoding, errors='strict')A bytes object holds raw data: a sequence of whole numbers from 0 to 255. Images, zip files, network messages and text saved to disk are all bytes underneath. Python writes bytes like b'Hi!': the b in front tells you it is bytes, not a string.
Text and bytes are different things. A string holds characters; to store or send it, it must be encoded into bytes, usually with UTF-8. "café".encode("utf-8") gives 5 bytes for 4 characters, because é needs two. .decode() goes back.
bytes() can build bytes from a list of numbers, from a string plus an encoding, or as a block of zeros. Bytes cannot be changed after they are made; use bytearray() for a changeable version.
Parameters
| Parameter | What it is |
|---|---|
sourceoptional | What to build from: a list of numbers 0-255, a string (then encoding is required), or a whole number n for n zero bytes. Empty gives b''. |
encodingoptional | Only when source is a string: the encoding to use, such as "utf-8". |
errorsoptional, default 'strict' | What to do with characters the encoding cannot store: "strict" raises an error, "replace" puts ? instead, "ignore" drops them. |
Return value
A new bytes object.
Examples
1From numbers and back
data = bytes([72, 105, 33])
print(data)
print(data[0])
print(list(data))b'Hi!' 72 [72, 105, 33]
Each item is a number. Python shows printable ones as letters to make bytes easier to read.
2Text to bytes and back
bytes(text, encoding) and text.encode(encoding) do the same thing.
text = "café"
data = text.encode("utf-8")
print(data)
print(len(text), "characters,", len(data), "bytes")
print(bytes(text, "utf-8") == data)
print(data.decode("utf-8") == text)b'caf\xc3\xa9' 4 characters, 5 bytes True True
\xc3\xa9 is the two-byte UTF-8 code for é, shown in hex.
3A block of zero bytes
blank = bytes(4)
print(blank)
print(len(blank))b'\x00\x00\x00\x00' 4
4Read a file as bytes
Mode "rb" gives the file's exact bytes, with no decoding.
with open("tag.dat", "rb") as f:
data = f.read()
print(data)
print(type(data).__name__, len(data))
print(data.hex(" "))b'OK42' bytes 4 4f 4b 34 32
Common mistakes
Mixing bytes and str
You cannot join bytes and a string with +. Encode the string, or decode the bytes, so both sides are the same type.
header = b"ID:"
try:
print(header + "42")
except TypeError:
print("TypeError: cannot add str to bytes")
print(header + "42".encode())
print(header.decode() + "42")TypeError: cannot add str to bytes b'ID:42' ID:42
Trying to change a byte
Bytes are immutable. Copy them into a bytearray() to change single values.
data = b"cat"
try:
data[0] = ord("b")
except TypeError:
print("TypeError: bytes cannot change")
buf = bytearray(data)
buf[0] = ord("b")
print(bytes(buf))TypeError: bytes cannot change b'bat'
Questions people ask
How do I convert bytes to a string in Python?
data.decode("utf-8"). Use the encoding the bytes were made with; UTF-8 is the usual one.
What is the difference between bytes and bytearray?
Same contents and methods, but bytearray can be changed in place (buf[0] = 65, buf.append(10)), while bytes cannot.
What does the b before a string mean?
b"..." is a bytes literal: the value is bytes, not text. It may contain only ASCII characters; other values are written as escapes such as \xc3.
How do I print bytes as hex?
data.hex() gives '4f4b'; data.hex(" ") puts a space between bytes.