Choose Encoding Error Policies
Core idea
The default strict error policy raises UnicodeError subclasses when conversion fails. replace substitutes a marker; ignore silently removes unconvertible data. Use lossy policies only when explicitly acceptable, such as a diagnostic preview.
try: b"A\xffB".decode("utf-8")except UnicodeDecodeError as err: print(err.start, err.end)The exception marks the offending byte span; end is exclusive.
Compare lossy policies
raw = b"A\xffB"print(raw.decode("utf-8", errors="replace") == "A\ufffdB")print(raw.decode("utf-8", errors="ignore"))Replacement preserves evidence of a problem; ignoring removes it. Neither recovers the original text.
Common mistake
Do not silently ignore malformed input in identifiers or records. Reject or quarantine it, retain the original bytes and report the error according to the application policy.
Practice
Decode b"X\xffY" using strict, replace and ignore. Record which conversions lose information.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Encoding errors
Check your understanding of encoding error policies.
Which exception occurs?
b"\xff".decode("utf-8")What is printed?
print(b"X\xffY".decode("utf-8", errors="ignore"))Which policy is normally appropriate for identifier imports?
What does replace do when decoding malformed UTF-8?