Skip to content
Tutorials Center
My learning

Topics

Python Reference Β· Numbers and Binary Data

Python bytes and bytearray methods

Reference for bytes and bytearray methods: decode(), hex(), fromhex(), split(), join(), find(), replace(), strip(), plus the mutating bytearray methods.

bytes (immutable) and bytearray (mutable) share almost the same method set. Many of them mirror string methods (split, replace, strip, startswith, find...), but they work on integers 0-255 and take bytes-like arguments, never str. A few are special: decode() turns bytes into text, hex() and fromhex() convert to and from hexadecimal, and bytearray adds in-place methods such as append() and extend().

Methods on bytes return new bytes; the same methods on bytearray return new bytearray objects and leave the original unchanged, except the mutating ones listed below.

Python
b"a,b".split(b",")       # [b'a', b'b']
b"Hi".hex()              # '4869'
bytes.fromhex("4869")    # b'Hi'

Try it

Python Text, hex and search

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 Mutating bytearray methods

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

Method Description
b.decode(encoding="utf-8", errors="strict") Return a str. errors can be "strict", "ignore", "replace", "backslashreplace" and more.
b.hex(sep=None, bytes_per_sep=1) Return a hexadecimal str of the bytes, with an optional separator.
bytes.fromhex(s) / bytearray.fromhex(s) Class method: build from a hex string; ASCII whitespace is ignored.
split, rsplit, splitlines, partition, rpartition Break into pieces, like the str versions.
join(iterable) Join bytes-like items using b as the separator.
find, rfind, index, rindex, count, startswith, endswith Searching. find returns -1 when missing, index raises ValueError.
replace, strip, lstrip, rstrip, removeprefix, removesuffix Return modified copies.
upper, lower, title, capitalize, swapcase ASCII-only case mapping.
isalpha, isdigit, isalnum, isspace, isupper, islower, isascii ASCII-only tests.
ljust, rjust, center, zfill, expandtabs Padding.
translate(table, delete=b""), bytes.maketrans(a, b) Byte-for-byte mapping.
bytearray only: append, extend, insert, pop, remove, reverse, clear, copy In-place edits (copy returns a new bytearray).

Raises: TypeError when a method receives a str where bytes are required; ValueError for invalid hex digits in fromhex or a value outside 0-255; UnicodeDecodeError from decode() when the bytes are not valid in the chosen encoding.

Usage notes

  • Never mix str and bytes. b"a" + "b" and b"a" == "a" do not do what you expect (the comparison is just False). Encode or decode explicitly.
  • ASCII only. Case and is... methods affect only ASCII letters; non-ASCII bytes are left alone. Decode to str for real Unicode handling.
  • Indexing gives integers, slicing gives bytes: b"AB"[0] is 65, b"AB"[0:1] is b'A'.
  • bytes is immutable. Code like data[0] = 1 fails with TypeError. Use bytearray for in-place edits, or memoryview for zero-copy slices.
  • decode() defaults to strict UTF-8, so unexpected input raises. Use errors="replace" when you only need a readable approximation, and never silently ignore data you must keep intact.
  • hex() with a separator works from the right when bytes_per_sep is positive and from the left when it is negative.
  • Joining: b"".join(chunks) is the fast way to build one bytes from many; repeated += on bytes copies every time.