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

ParameterDescription
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

Text to bytes and backTry it yourself
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é
From integers and backTry it yourself
print(bytes([65, 66, 67]))
print(bytes(4))
print(list(b"AB"))

Output

b'ABC'
b'\x00\x00\x00\x00'
[65, 66]
Hex stringsTry it yourself
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" raises TypeError. Encode text (.encode()) or decode bytes (.decode()) first.
  • Indexing returns an int: b"A"[0] is 65, not b"A".

Version history

VersionChange
Python 3.0Added