decode Error Strategies For Messy Bytes
bytes.decode picks an error strategy: strict raises UnicodeDecodeError, replace marks bad bytes, ignore drops them, backslashreplace keeps the evidence.
Code
raw = b"caf\xe9 \xff\xfe done"
# strict mode: bad bytes raise UnicodeDecodeError outright, never silently turning into mojibake
try:
raw.decode("utf-8")
except UnicodeDecodeError as exc:
print("strict raises:", exc.reason)
# replace: bad bytes become U+FFFD placeholders, so log parsing never breaks
print("replace:", raw.decode("utf-8", errors="replace"))
# ignore: bad bytes are dropped; backslashreplace: they are kept as escaped evidence
print("ignore:", raw.decode("utf-8", errors="ignore"))
print("backslashreplace:", raw.decode("utf-8", errors="backslashreplace"))
# surrogateescape: bad bytes map to surrogate characters, and encoding back restores them losslessly
roundtrip = raw.decode("utf-8", errors="surrogateescape").encode("utf-8", errors="surrogateescape")
print("surrogateescape roundtrip equals raw:", roundtrip == raw)How it works
UnicodeDecodeError is not tied to any input check: it fires whenever execution reaches that line.
Top-level bindings raw, roundtrip hold the demo state — nothing sits inside a function scope.
Using it
The run emits 5 labeled sections — strict raises:, replace:, ignore:, backslashreplace:, surrogateescape roundtrip equals raw: — one per step.
Key statements
except UnicodeDecodeError as exc:
print("strict raises:", exc.reason)
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- Does the snippet validate its input?
- No. There is no input validation in the snippet — the `UnicodeDecodeError` is raised unconditionally at its site, with no check in front of it.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `raw`, `roundtrip`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.