prize18-1 Exercise 3: Make Garbled Text, Then Repair It ========================================================= Idea: garbled text ("mojibake") appears when bytes written with one encoding are read with another. UTF-8 bytes read as Latin-1 give two odd characters where one accented letter should be. Because Latin-1 maps every byte to a character, the damage can be reversed by encoding back to Latin-1 (recovering the original bytes) and decoding as UTF-8. ex3.py: original = "na\u00efve caf\u00e9" raw = original.encode("utf-8") print("bytes:", raw) garbled = raw.decode("latin-1") print("decoded as latin-1:", garbled) repaired = garbled.encode("latin-1").decode("utf-8") print("repaired:", repaired, repaired == original) try: raw.decode("ascii") except UnicodeDecodeError as e: print("ascii error:", e) Real output (Python 3.14): bytes: b'na\xc3\xafve caf\xc3\xa9' decoded as latin-1: naïve café repaired: naïve café True ascii error: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128) Caveat: this repair only works when no information was lost. If the garbled text was saved through a step that replaced or dropped bytes, no code can fully recover it.