Python 3 reference · Built-in Functions
Python bytes() Function
Create an immutable sequence of bytes: raw binary data such as file contents, network messages or encoded text.
Python 3 Since 3.0
Syntax
bytes(source=b"")
bytes(source, encoding, errors="strict")
Parameters
| Parameter | Description |
|---|---|
source optional |
An int (size), a str (needs encoding), an iterable of ints 0–255, or a buffer. |
encoding optional |
Used to encode a str source. |
errors optional |
How to handle encoding errors. Default: "strict" |
Return value
A new immutable bytes object.
Examples
print(bytes("café", "utf-8"))
print("café".encode()) # the usual way to encode text
print(b"caf\xc3\xa9".decode()) # and back to text
Output
b'caf\xc3\xa9' b'caf\xc3\xa9' café
print(bytes([65, 66, 67]))
print(bytes(4))
print(list(b"AB"))
Output
b'ABC' b'\x00\x00\x00\x00' [65, 66]
data = bytes.fromhex("48 65 6c 6c 6f")
print(data, data.hex(" "))
Output
b'Hello' 48 65 6c 6c 6f
Common mistakes
- Text and bytes don't mix:
"a" + b"b"raisesTypeError. Encode text (.encode()) or decode bytes (.decode()) first. - Indexing returns an int:
b"A"[0]is65, notb"A".
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
bytearray()· Create a mutable sequence of bytes (integers 0–255). Like bytes, but you can change, append and remove bytes in place.str()· Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.memoryview()· Create a view of an object's binary data (bytes, bytearray, arrays) that slices and edits it without copying.- Python Data Types · tutorial
- Python File Handling · tutorial