bytes() Immutable byte sequence
Last updated: 2026-09-22
bytes() Immutable byte sequence
bytes() returns an immutable bytes object; constructible from a bytes-like source, a string + encoding, or an iterable of ints.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
bytes([source[, encoding]]]])
⚙️ Parameters
| source Optional | Optional: an int, string, iterable of ints, or bytes-like object.(Default:None) |
|---|---|
| encoding Optional | Encoding name used when source is a str, e.g. 'utf-8'.(Default:None) |
| errors Optional | Error-handling scheme for encoding, e.g. 'strict' / 'ignore'.(Default:None) |
Returns:bytes. An immutable bytes object.
💥 Raises
TypeError— Raised when source has an unsupported type.ValueError— Raised when an element is outside 0-255.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
b'hello'
b'\xe4\xb8\xad'
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat does bytes(5) return? Many people assume it is b'5'.
AIt returns b'\x00\x00\x00\x00\x00'. An integer argument means length, producing that many zero bytes — not the string form of the number.
QWhat is the difference between bytes() and bytearray()?
AThe core difference is mutability: bytes is immutable, bytearray is mutable. The remaining construction rules (integer, string+encoding, iterable of integers) are the same.
QWhy does bytes('中文') raise an error?
AConstructing bytes from a string requires an encoding: bytes('中文', encoding='utf-8'). Otherwise it raises a TypeError saying encoding is missing.
QHow do I convert bytes back to a string?
AUse the decode() method, e.g. b'\xe4\xb8\xad'.decode('utf-8') returns '中'. The equivalent is str(b, encoding='utf-8').