← 中文资源

简体中文版本

decode 的错误处理策略

bytes.decode 的 errors 策略各有用途:strict 抛异常、replace 换占位符、ignore 丢弃、backslashreplace 保留转义证据,选错策略日志就会出现静默乱码。

阅读英文原文

实现说明

UnicodeDecodeError 不与任何输入检查绑定:执行到达那一行就会触发。 顶层就这几处状态:raw、roundtrip。

使用要点

  • 演示输出是带标签的(strict raises:、replace:、ignore:),每个操作都会留下自己的一行标注。

常见问题

这个示例会校验输入吗?

不会。示例里没有输入校验——UnicodeDecodeError 在其所在位置无条件抛出,前面没有任何检查。

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件的状态由几个模块级绑定持有:raw、roundtrip。

核心语句

except UnicodeDecodeError as exc:
    print("strict raises:", exc.reason)

代码示例

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)