Skip to contentSkip to navigation

Module 17 · Lesson 02

Text Encodings and Binary Data

Understand the difference between text and bytes: Unicode code points, UTF-8, encode and decode with error handling, mojibake, bytes and bytearray, binary files, and packing binary records with struct.

  • About 10 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Characters and code points
  • encode and decode
  • Bad bytes and error handling
  • Watch text become bytes

Text is not bytes

Python text is made of characters; files and networks carry bytes. Encoding turns one into the other.

  • Code points

    Every character has a number: ord("A") is 65.

  • UTF-8

    The usual encoding for files and the web. It can store every character.

  • encode, decode

    text.encode("utf-8") gives bytes. data.decode("utf-8") gives text back.

  • bytes

    b"hi" is a sequence of numbers from 0 to 255, not of characters.

Bytes everywhere

Under every file, picture and message are bytes.

  • Web pagesA page arrives as bytes, and the browser decodes it as UTF-8.
  • ImagesEvery PNG file starts with the same eight bytes, so programs can recognise it.
  • Sound filesAudio is stored as numbers packed into bytes, thousands every second.
  • EmojiOne emoji can be several code points, and four or more bytes.

Turning bytes back into text

This line decodes bytes from a file, safely. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

text:A str again: characters, ready to print or compare.

Cross between text and bytes

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Characters and numbers

ord() gives a character's number, chr() goes the other way.

Your turn: Print the code point of the first letter of your name.

Python
for ch in "Aé€":
    print(ch, ord(ch), hex(ord(ch)))
print(chr(65), chr(9731))
Output
Press Run to see what it prints.

Watch text become bytes

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. word = "été"
  2. data = word.encode("utf-8")
  3. first = data[0]
  4. back = data.decode("utf-8")
  5. print(len(word), len(data))
  6. print(first, back == word)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.One code point further:

print(chr(ord("a") + 1))

0 of 6 answered

Common encoding misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Characters, code points and bytes

A Python str is a sequence of characters. Each character has a number, its code point, given by the Unicode standard, which covers every writing system in use. ord gives a character's code point and chr goes back:

Try it 1: edit me, then Run
print(ord("A"), ord("é"), ord("€"))   # 65 233 8364
print(chr(8364))                      # €
Output
Press Run to see what it prints.

Computers store and send bytes: numbers from 0 to 255. An encoding is a rule for turning code points into bytes and back. Text inside your program is just characters; bytes only appear at the edges, where data goes to files, networks or other programs.

UTF-8

The encoding you should use almost everywhere is UTF-8. It uses one byte for the 128 ASCII characters (English letters, digits, common punctuation) and two, three or four bytes for everything else:

Try it 2: edit me, then Run
for ch in ["A", "é", "€", "𝄞"]:
    print(ch, len(ch.encode("utf-8")))   # 1, 2, 3, 4 bytes
Output
Press Run to see what it prints.

So the length of a string in characters and its length in bytes can differ: len("café") is 4 but len("café".encode("utf-8")) is 5. Limits such as "a database column holds 255 bytes" or "an SMS holds 140 bytes" count bytes, not characters.

encode and decode

Try it 3: edit me, then Run
data = "Café".encode("utf-8")
print(data)                  # b'Caf\xc3\xa9'
print(data.decode("utf-8"))  # Café
Output
Press Run to see what it prints.

str.encode(encoding) gives bytes; bytes.decode(encoding) gives str. A bytes value is printed with a b prefix; bytes that are not printable ASCII are shown as \x and two hex digits. Here é became the two bytes c3 a9. UTF-8 is the default when you leave the encoding out, but writing it makes your intent clear.

When decoding goes wrong

Not every sequence of bytes is valid UTF-8. Decoding invalid data raises UnicodeDecodeError:

Try it 4: edit me, then Run
old = "café".encode("latin-1")    # b'caf\xe9': one byte for é
old.decode("utf-8")               # UnicodeDecodeError
Output
Press Run to see what it prints.

The errors argument chooses what to do instead:

  • errors="strict" (the default): raise the error.
  • errors="replace": put the replacement character � where bytes were bad, so you can see that something was lost.
  • errors="ignore": drop the bad bytes silently. Use with care.

The nastier problem is decoding with the wrong encoding that happens not to fail. Every byte is valid Latin-1, so decoding UTF-8 bytes as Latin-1 never raises; it produces mojibake, garbled text such as Müller. The fix is never to guess: know which encoding the data uses, ideally UTF-8 everywhere, and state it explicitly.

Working with bytes

bytes looks like a string but behaves like a sequence of small integers:

Try it 5: edit me, then Run
data = b"Hi!"
print(data[0])          # 72: indexing gives an int
print(data[:2])         # b'Hi': slicing gives bytes
print(list(data))       # [72, 105, 33]
print(data.hex(" "))    # 48 69 21
print(bytes.fromhex("48 69"))   # b'Hi'
Output
Press Run to see what it prints.

bytes is immutable, like str. bytearray is its mutable twin: you can change items, append and extend, which suits building binary data piece by piece. You cannot mix the two worlds: b"id:" + "42" raises TypeError. Encode the text first, or decode the bytes.

Integers convert to and from fixed-size bytes with int.to_bytes and int.from_bytes, giving the length and the byte order: "big" puts the most significant byte first, "little" the least significant.

Files: text mode and binary mode

open has two modes. In text mode (the default) Python encodes and decodes for you, so always say which encoding:

Try it 6: edit me, then Run
with open("names.txt", "w", encoding="utf-8") as f:
    f.write("Zoë\n")
Output
Press Run to see what it prints.

Without encoding=, Python uses a platform default that differs between computers, the classic cause of a file that works on one machine and fails on another.

In binary mode, "rb" or "wb", there is no encoding at all: you read and write bytes exactly as stored. Use it for images, audio, archives, and any format that is not text. Many binary formats start with a fixed signature: PNG files begin with the bytes 89 50 4E 47, and checking those bytes is how programs recognise a file type regardless of its name.

Binary records with struct

Devices and file formats often store numbers in fixed-size binary records. The struct module packs Python values into bytes and unpacks them again, following a format string:

Try it 7: edit me, then Run
import struct
record = struct.pack("<Hh", 7, -215)       # unsigned 2-byte, signed 2-byte
print(record.hex(" "), struct.unpack("<Hh", record))
Output
Press Run to see what it prints.

< means little-endian; H is an unsigned 16-bit integer, h a signed one, B a single unsigned byte and f a 4-byte float. struct.calcsize(format) tells you how many bytes a record takes.

Base64: bytes as safe text

Some channels, such as JSON or email, only carry text. base64.b64encode(data) turns any bytes into ASCII letters and digits, about a third larger, and b64decode turns them back. It is an encoding for transport, not encryption: anyone can decode it.

Syntax

The general shape of the statements in this lesson.

syntax.py
ord("é")  chr(233)                  # code points
data = text.encode("utf-8")          # str -> bytes
text = data.decode("utf-8")          # bytes -> str
data.decode("utf-8", errors="replace")   # or "ignore", "strict"
b"abc"[0]   b"abc"[:2]   list(b"ab") # int, bytes, ints
data.hex(" ")   bytes.fromhex("ff 00")
buf = bytearray(); buf += b"x"       # mutable bytes
(258).to_bytes(2, "big")   int.from_bytes(b"", "big")
open(path, "w", encoding="utf-8")    # text: always give encoding
open(path, "rb")                     # binary: bytes in, bytes out
struct.pack("<Hhf", 1, -2, 3.5)      # H u16, h i16, B u8, f float
struct.unpack("<Hhf", data)
base64.b64encode(data)               # bytes -> ASCII-safe bytes
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Characters versus bytes

Beginner

For several words, print the number of characters, the number of UTF-8 bytes and the bytes in hex. Then cut a message to fit a 10-byte limit without splitting a character in half.

Python
words = ["tea", "café", "naïve", "€5", "日本"]
for word in words:
    data = word.encode("utf-8")
    print(f"{word:<6} {len(word)} chars {len(data)} bytes  {data.hex(' ')}")

message = "Grüße aus Köln"
limit = 10
raw = message.encode("utf-8")
cut = raw[:limit].decode("utf-8", errors="ignore")
print(repr(raw[:limit]))
print(repr(cut), len(cut.encode("utf-8")), "bytes")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

ASCII letters take one byte, accented Latin letters two, and the euro sign and the Japanese characters three each. Slicing the bytes at 10 cuts the two-byte ß in half, so decoding with errors="ignore" drops the broken half and keeps whole characters only, giving a string that fits the limit.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Decoding with the wrong encoding

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
data = 'Müller'.encode('utf-8')
print(data.decode('latin-1'))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints Müller (mojibake) with no error

Write this instead

data = 'Müller'.encode('utf-8')
print(data.decode('utf-8'))

Why it happens

Every byte is valid Latin-1, so the two UTF-8 bytes of ü are read as two separate characters.

In the real world

Where this shows up in software people use every day.

  1. Decoding sensor records

    Internet of things

    Greenhouse sensors send compact 6-byte readings over a low-power radio: a sensor id, the temperature in tenths of a degree (which can be negative), the humidity percentage and a checksum byte. The collector unpacks them with struct and drops readings whose checksum does not match.

    Why Python fits

    The format string describes the record exactly, so pack and unpack agree on every byte, and calcsize gives the 6-byte step for slicing the stream. The signed h handles the negative temperature. The simulated radio damage flips one byte of the third record, its checksum no longer matches, and it is dropped instead of reporting a wrong reading.

    Python
    import struct
    
    RECORD = "<HhBB"    # little-endian: u16 id, i16 tenths of a degree, u8 humidity, u8 checksum
    SIZE = struct.calcsize(RECORD)
    
    def make(sensor, tenths, humidity):
        body = struct.pack("<HhB", sensor, tenths, humidity)
        return body + bytes([sum(body) % 256])
    
    def read(packet):
        sensor, tenths, humidity, check = struct.unpack(RECORD, packet)
        if sum(packet[:-1]) % 256 != check:
            raise ValueError(f"bad checksum from sensor {sensor}")
        return sensor, tenths / 10, humidity
    
    stream = make(3, 215, 64) + make(7, -42, 91) + make(9, 180, 55)
    stream = stream[:16] + bytes([stream[16] ^ 0xFF]) + stream[17:]   # damage one byte
    
    print("record size:", SIZE, "bytes;", len(stream), "bytes received")
    for start in range(0, len(stream), SIZE):
        packet = stream[start:start + SIZE]
        try:
            sensor, temp, humidity = read(packet)
            print(f"sensor {sensor}: {temp:5.1f} C, {humidity}% humidity  [{packet.hex(' ')}]")
        except ValueError as error:
            print("dropped:", error)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

How do I find out which encoding a file uses?

Ideally from its documentation or the system that wrote it. Tools can guess from byte patterns, but a guess can be wrong. If a file decodes as UTF-8 without errors, it very probably is UTF-8.

What is the BOM I sometimes see at the start of files?

A byte order mark, the bytes ef bb bf, which some editors put at the start of UTF-8 files. Opening with encoding="utf-8-sig" removes it automatically when reading.

Is ASCII the same as UTF-8?

ASCII covers only 128 characters. Every ASCII file is also valid UTF-8 with the same bytes, which is one reason UTF-8 became the standard, but UTF-8 also covers every other character.

Does len() of an emoji give 1?

For a single code point, yes. Some emoji and accented letters are built from several code points joined together, so one visible symbol can have a length of 2 or more. Counting what a reader sees as characters needs extra care.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 13 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.