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.

PythonData Integrity

Code

pythonsnippet
18 lines
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

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`.