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.

CategoryBuilt-in Functions
KindBuilt-in Function
Python Versionall

📝 Syntax

bytes([source[, encoding]]]])

⚙️ Parameters

source OptionalOptional: an int, string, iterable of ints, or bytes-like object.(Default:None)
encoding OptionalEncoding name used when source is a str, e.g. 'utf-8'.(Default:None)
errors OptionalError-handling scheme for encoding, e.g. 'strict' / 'ignore'.(Default:None)

Returns:bytes. An immutable bytes object.

💥 Raises

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

b'hello'
b'\xe4\xb8\xad'
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').
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏