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
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.
for ch in "Aé€":
print(ch, ord(ch), hex(ord(ch)))
print(chr(65), chr(9731))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.
- word = "été"
- data = word.encode("utf-8")
- first = data[0]
- back = data.decode("utf-8")
- print(len(word), len(data))
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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 bytesPress 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
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.
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")Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
data = 'Müller'.encode('utf-8')
print(data.decode('latin-1'))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Internet of things
Decoding sensor records
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
packandunpackagree on every byte, andcalcsizegives the 6-byte step for slicing the stream. The signedhhandles 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.Pythonimport 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)OutputPress 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?
What is the BOM I sometimes see at the start of files?
Is ASCII the same as UTF-8?
Does len() of an emoji give 1?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.