Encoding and Decoding Text Files
Encoding turns text into bytes according to a named convention. A reader uses the same convention to recover the text.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Measure a short record
The text café has four Python code points and takes five UTF-8 bytes because é occupies two. A text writer and its reader can agree on UTF-8 explicitly. See strings and bytes for why both measurements can be correct.
Test the actual bytes
A check using only ASCII works for several encodings and can miss a mismatch. Include a non-ASCII example and compare it with independently known bytes. Round-trip tests address symmetric mistakes between a writer and reader.[1]
Round-trip an accented letter and its exact bytes
The text "café" encodes as 63 61 66 C3 A9 in UTF-8. A decoder using UTF-8 returns the original four letters. Treating the two non-ASCII bytes as separate Latin-1 characters instead gives a visibly different string. Check code points or bytes when the visual output is ambiguous. See Unicode positions.
UTF-8 bytes: 63 61 66 C3 A9
Byte length: 5
Unicode code-point count: 4
Decode with UTF-8: café
Distinguish exact text equality from a visual match
A text containing a decomposed accent can display identically while differing by code points and bytes. If exact round trips matter, compare original and decoded strings without normalization. If canonical comparison is desired, apply it separately.