Skip to content
Tutorials Center
My learning

Topics

Python Reference · Built-in Functions

Python bytes() function

Reference for Python bytes(): create immutable byte sequences from a size, integers, a string with an encoding or a buffer, and convert to and from text.

bytes is the immutable sequence type for raw binary data: each item is an integer from 0 to 255. Files opened in binary mode, network packets, hashes and encoded text are all bytes.

Besides the literal form b"abc" (ASCII characters only), you can call bytes() to build one from a size, a list of integers, a string with an encoding, or another buffer.

Python
bytes([72, 105])         # b'Hi'
"café".encode("utf-8")   # b'caf\xc3\xa9'

Try it

Python Creating bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Hex, immutability and decoding errors

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
bytes()
bytes(size)
bytes(iterable_of_ints)
bytes(string, encoding)
bytes(string, encoding, errors)
bytes(buffer)
Name Description
size A non-negative int: that many zero bytes.
iterable_of_ints Integers in the range 0-255.
string A str; needs encoding.
encoding A codec name such as "utf-8", "ascii", "latin-1".
errors "strict" (default), "ignore", "replace", "backslashreplace", ...
buffer Any object supporting the buffer protocol (bytes, bytearray, memoryview, ...).

Return value: a new immutable bytes object.

Raises: TypeError for a string without an encoding or an unsupported type; ValueError for integers outside 0-255.

Usage notes

  • Indexing gives integers. b"abc"[0] is 97; slicing gives bytes. Use b"abc"[0:1] to get a one-byte bytes.
  • Literals are ASCII only. b"café" is a syntax error. Encode a str instead.
  • bytes(5) is five zero bytes, not the text "5". Use str(5).encode() for that.
  • Encoding vs decoding. str.encode() produces bytes; bytes.decode() produces text. Always name the encoding when files or protocols are involved, and prefer UTF-8.
  • Immutable and hashable. You can use bytes as a dictionary key. For in-place edits use bytearray.
  • Helpful methods. hex(), bytes.fromhex(), split, replace, startswith, find, and int.from_bytes() / int.to_bytes() for numbers.
  • str(b"x") is a repr, not a decode. str(b"hi") returns "b'hi'". Call .decode().
  • Mixing types. b"a" + "b" raises TypeError; keep bytes and text apart.