Python Bytes

Beginner
8 min read
Updated: Nov 2026
3 examples
Binary data

Definition and Usage

In Python, bytes is an immutable sequence of integers from 0 to 255. It stores raw binary data: the contents of an image file, a network packet, a checksum, or text that has already been encoded with a codec such as UTF-8.

You write a bytes literal with a b prefix: b"GET" or b'\x89PNG'. Only ASCII characters may appear in the literal itself; any other value is written as an escape such as \xff. You can also build bytes with the bytes() built-in, and you get bytes back from "text".encode("utf-8") or from reading a file opened in "rb" mode.

This page explains what bytes are and the rules every bytes method follows. The Bytes Methods index lists every method guide (find(), split(), decode(), and more).

Indexing gives an int, slicing gives bytes.

b"Hi"[0] is the number 72, but b"Hi"[0:1] is b'H'. This surprises most beginners coming from str, where both give a one-character string.

Python Syntax

Create bytes, read values, and call methods with dot notation:

Python
data = b"Hello"                    # bytes literal
size = len(data)                   # 5: number of bytes
first = data[0]                    # 72: indexing gives an int
part = data[1:3]                   # b'el': slicing gives bytes
loud = data.upper()                # b'HELLO': a new object
text = data.decode("ascii")        # 'Hello': back to str
print(size, first, part, loud, text)

bytes vs str vs bytearray

Python keeps text and binary data in separate types. Pick the one that matches your data:

TypeHoldsRemember
strUnicode text, for example "caf\u00e9"Immutable; .encode("utf-8") turns it into bytes
bytesRaw values 0 to 255, for example b"caf\xc3\xa9"Immutable and hashable; .decode("utf-8") turns it into text
bytearrayThe same values as bytesMutable: supports buf[0] = 65, append(), and extend()
memoryviewA window onto another object's bytesZero-copy slicing of large buffers; accepted wherever bytes-like is allowed

Common uses for bytes: reading and writing binary files, checking file signatures (magic numbers) such as b"\x89PNG", sending and receiving data over sockets, hashing with hashlib, and building or parsing binary protocols.

Rules Every Bytes Method Follows

RuleWhat it means
New object every timebytes is immutable, so methods like replace() and strip() return a new bytes object; keep the result in a variable.
Bytes-like arguments onlyPass b"x", a bytearray, or a memoryview. A str argument such as data.find("x") raises TypeError.
ASCII-only case and checksupper(), isalpha(), isspace(), and friends only know ASCII letters, digits, and whitespace. Bytes 128 to 255 are never changed and never count as letters.
Same methods on bytearrayCalled on a bytearray, methods that build data return a bytearray instead of bytes.
Text needs decode()To use full Unicode rules, call decode() first, work with the str, then encode again.

Python Examples

Three short programs that show how bytes behave in everyday Python.

Example 1 — Indexing, Slicing, and Looping Over bytes

See the three ways to look inside a bytes object: as a whole, one value at a time, and as smaller bytes slices.

Python
data = b"Hi!\n"

print(data)
print(len(data), data[0], data[-1])
print(data[:2], data[1:2])
print(list(data))
print(data.upper(), data)

How It Works

  1. Repr with escapes. Printing bytes shows a b'...' literal: printable ASCII appears as characters and the newline byte appears as \n.
  2. Four bytes, four ints. len() counts bytes, data[0] is 72 (the code for H), and data[-1] is 10, the newline.
  3. Slices stay bytes. Even the one-byte slice data[1:2] is the bytes object b'i', not an int.
  4. Methods copy. upper() returns b'HI!\n' while data itself still prints as before.

Example 2 — Encoding Text to bytes and Decoding It Back

Encode a word with a non-ASCII letter, compare its length in characters and in bytes, and see how ASCII-only case rules treat the encoded form.

Python
text = "na\u00efve"
data = text.encode("utf-8")

print(data)
print(len(text), len(data))
print(data.decode("utf-8") == text)
print(data.upper())
print(ascii(data.decode("utf-8").upper()))

How It Works

  1. One letter, two bytes. UTF-8 stores the letter i with diaeresis (U+00EF) as \xc3\xaf, so five characters become six bytes.
  2. Lossless round trip. decode("utf-8") rebuilds exactly the original string, so the comparison is True.
  3. ASCII-only upper(). On bytes, only n, a, v, and e change; the two non-ASCII bytes pass through untouched.
  4. Unicode rules need str. Decoding first and calling str.upper() also converts the accented letter to U+00CF, shown by ascii() as \xcf.

Example 3 — Arguments Must Be bytes-like, Not str

Search an HTTP request line, see the error a str argument causes, and pass a bytearray instead.

Python
header = b"GET /index.html HTTP/1.1"

try:
    header.startswith("GET")
except TypeError:
    print("str argument rejected: use b'GET'")

print(header.startswith(b"GET"))
print(header.split(b" ")[1])
buf = bytearray(b"ok")
print(buf.upper(), header.find(bytearray(b"HTTP")))

How It Works

  1. No mixing types. startswith() on bytes refuses the str "GET" and raises TypeError.
  2. Bytes argument works. With b"GET" the check succeeds, and split(b" ") returns a list of bytes fields.
  3. bytearray in, bytearray out. Calling upper() on a bytearray returns a new bytearray.
  4. Any bytes-like argument. find() accepts a bytearray needle and reports that HTTP starts at offset 16.

Next: Python Bytes Methods by Group

Full list with short descriptions: Python Bytes Methods index (/python/bytes/method).

Frequently Asked Questions

A bytes object is an immutable sequence of integers from 0 to 255. It holds raw binary data such as file contents, network packets, or text after it has been encoded. You write one with a b prefix, for example b"Hi".
str holds Unicode text made of characters; bytes holds raw byte values. Convert text to bytes with text.encode("utf-8") and bytes back to text with data.decode("utf-8"). The two types never mix: b"a" + "b" raises TypeError.
Indexing a bytes object returns the byte value as an int, so b"A"[0] is 65. Slicing returns bytes, so b"A"[0:1] is b'A'.
No. bytes is immutable, so every method returns a new object and item assignment raises TypeError. Use bytearray when you need to modify data in place.
Bytes case methods only know ASCII letters a-z and A-Z. Bytes from 128 to 255 are not letters to them, so they pass through unchanged. Decode to str first if you need full Unicode case rules.

Browse every bytes method

Open the method index for categorized guides with examples and FAQs.

Bytes Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful