Unicode assigns code points to characters. An encoding, such as UTF-8, specifies how text is converted to and from bytes.
Inspect byte sequences, byte-order marks and decoding failures without confusing a successful decode with a correct encoding guess.
Two bytes, c3 a9, can become é or é without either decoder raising an error. The missing information is the encoding contract. Follow bytes into characters first; then investigate how a program should record a fallback and compare equivalent spellings.

Decode a Windows export that isn't UTF-8
Suppose an older exporter declares cp1252, while your importer assumes
UTF-8. UTF-8 has strict rules about which bytes can follow which, so most
wrong guesses crash loudly:
UnicodeDecodeErrorRead the error — it names the byte it choked on and its position. Then decode with the encoding that was actually used.
But the dangerous case is quieter. The bytes happen to be valid in the wrong encoding too, and nothing fails — you just get the wrong text:
print("café".encode("utf-8").decode("latin-1"))Once you've seen é, ï and ’, you'll recognise them forever — UTF-8
bytes read as a single-byte Western encoding. Quarry's decoder tries the
strongest evidence first: utf-8, then cp1252 (a known legacy source encoding in these fixtures), falling back to latin-1 as a last resort — because
Latin-1 maps every one of the 256 byte values to some character, so it
can never raise. That's exactly why it's last, not first: never crashing is
not the same as being right, and a guess should be visible, not silent.
You can also choose what a decode does with bytes that don't fit, through
errors=:
replace is honest — the � marks exactly where information was lost, and
you can count them. ignore quietly deletes data and should make you
nervous every time you reach for it.
Preparing this topic’s interactive investigation…
Watch a string's byte cost, character by character
UTF-8 is a variable-width code: ASCII costs one byte, and everything above it costs more. Step through a string one character at a time and watch the byte cost of each:
Five characters, seven bytes: the rupee sign alone costs three. That's why
len() of a str and len() of the bytes it encodes to can disagree —
one counts code points, the other counts bytes.
Read an export with a byte-order mark
A stray  glued to the first column name is a BOM: the bytes
EF BB BF, which some tools put at the start of a UTF-8 file to announce
"this is UTF-8". Decoded as plain utf-8 it survives as an invisible
character; the utf-8-sig codec reads it and throws it away:
UTF-16 needs its mark more, because it has a real question to answer: is
each two-byte unit stored low byte first (FF FE) or high byte first
(FE FF)? The utf-16 codec reads the mark and picks the order for you —
trust it before anything else when it's there:
data = b"\xff\xfe\x68\x00\x69\x00"
print(data.decode("utf-16"))Separate decoding evidence from a decoding guess
The sequence c3 a9 is legal under UTF-8 and Latin-1. A successful decode therefore answers “is this byte sequence permitted by this codec?”, not “is this the codec the author used?”. The producer's declared encoding is stronger evidence than trying codecs until one succeeds.
Both lines print successfully. One yields one code point, the other two. Re-encoding with the same codec returns the original bytes in both cases, so a round-trip check cannot choose between them either. This is a useful counterexample to “no exception means correct”.
The exercise's UTF-8 → cp1252 → Latin-1 order is an explicit fallback policy for its sample sources, not universal encoding detection. A BOM supports a codec choice but does not prove the remaining bytes are well formed. Keep the original bytes and the chosen codec when recovery matters; replacing or ignoring invalid bytes discards evidence. Repairing mojibake by reversing cp1252 is appropriate only when that exact mistaken conversion is known.
Transfer to names: "é" and "e\u0301" can be canonically equivalent while having different code-point counts. A visual symbol may also span several code points, as with an emoji sequence. Thus len(str) is not a reliable count of user-perceived symbols. Normalize a comparison copy when the application's rules call for it; retain the original spelling for display. Design two tests: equivalent accented names should compare equal, and two genuinely different names should remain different. Normalization is a comparison policy, not permission to merge every look-alike.
Reference: Unicode representations, codecs and normalization.
Compare two spellings of the same accented name
One last surprise: é has two spellings in Unicode — the single code point
U+00E9, or a plain e followed by U+0301, a combining acute accent. They
render identically and == says they differ:
a = "é" # e + combining accent
b = "é" # é as one code point
print(a == b, len(a), len(b))unicodedata.normalize("NFC", s) composes a string into one canonical
spelling, and casefold() is lower() built for comparison — it also maps
ß to ss:
Quick practice
print(len("naïve".encode("utf-8")))UnicodeEncodeErrorRun it and read the UnicodeEncodeError. Then encode with a codec that can hold the character.
print("STRASSE".casefold() == "strasse".casefold(), "straße".casefold())data = "hé".encode("utf-8")
cleaned = data.decode("utf-8", errors="ignore")
print(cleaned == "hé", len(cleaned))🎯 Your turn
Build decode_source(hex_data):
decode_source("636166e9")→{"encoding": "cp1252", "text": "café"}decode_source("efbbbf636166c3a9")→{"encoding": "utf-8-sig", "text": "café"}
Hint — check the BOMs with startswith, then try utf-8 and cp1252 in a
try/except UnicodeDecodeError, and fall back to latin-1.
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write byte_lengths(text) returning [characters, utf8_bytes, utf16_bytes], where the UTF-16 count uses "utf-16-le" (no byte-order mark). byte_lengths("é") → [1, 2, 2].
Write to_hex(text, encoding) returning the encoded bytes as lowercase hex pairs separated by single spaces, or "unencodable" if the encoding can't represent the text. to_hex("hé", "utf-8") → "68 c3 a9".
Somebody decoded UTF-8 bytes as cp1252, so café became café. Write repair(text): re-encode with "cp1252" and decode with "utf-8". If either step fails, the text wasn't mojibake of that kind — return it unchanged.
"é" can be one code point or e plus a combining accent; they look identical and == says False. Write same_text(a, b) that returns True when the two are equal after unicodedata.normalize("NFC", ...) and .casefold().
Write sniff_all(samples) taking {name: hex} and returning {name: label}. Labels, checked in order: "utf-8-sig" (UTF-8 BOM), "utf-16" (either UTF-16 BOM), "binary" (contains a 00 byte), "ascii" (every byte below 0x80), "utf-8" (strict decode works), "cp1252" (that decode works), else "unknown".
A teammate notices that decoding with "latin-1" never raises, and proposes Quarry decode every file that way so it never crashes on bad input. Explain why it never raises, what it does to a UTF-8 file, and why a crash can be the better outcome.