Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

bytes()

Constructs an immutable byte sequence from a length, iterable of byte values, or buffer.

Version: Python 3.14; repository image, production runtime not attested

Syntax

bytes()
bytes(source)
bytes(string, encoding, errors="strict")

Constructs an immutable byte sequence from a length, iterable of byte values, or buffer.

An integer argument reserves that many zero bytes, whereas an iterable provides the actual byte values.

An integer source is a length, so 3 creates three zero bytes and hex shows six zero digits. An iterable instead supplies byte values: [3] creates just 03. Values must be from 0 through 255. Constructing from text requires an encoding; the resulting bytes are immutable.

assert bytes(3) == b"\x00" * 3 and bytes([3]) == b"\x03"
assert bytes("é", "utf-8").hex() == "c3a9"

Examples

print(bytes(3).hex())
print(bytes([3]).hex())

Result

000000
03

An integer source is a length, so 3 creates three zero bytes and hex shows six zero digits. An iterable instead supplies byte values: [3] creates just 03. Values must be from 0 through 255. Constructing from text requires an encoding; the resulting bytes are immutable.

Sources