示例工程 03-numbers-strings-unicode

另有 1 个文件未随站点发布(平台工程、二进制或超过 200KB)。

03-numbers-strings-unicode/03-encode-decode-errors/encode_decode_errors.py

python · 0.7 KB

"""演示 UTF-8 截断与 errors= 策略。"""
 
from __future__ import annotations
 
TEXT = "中文"
 
 
def utf8_bytes() -> bytes:
    return TEXT.encode("utf-8")
 
 
def truncated_last_byte() -> bytes:
    """去掉最后一个字节,制造不完整序列。"""
    return utf8_bytes()[:-1]
 
 
def decode_with(errors: str) -> str:
    """用指定 errors 策略解码截断字节。"""
    return truncated_last_byte().decode("utf-8", errors=errors)
 
 
def main() -> None:
    print(f"bytes: {utf8_bytes()!r} len={len(utf8_bytes())}")
    print("strict: raises UnicodeDecodeError")
    print(f"replace: {decode_with('replace')!r}")
    print(f"ignore: {decode_with('ignore')!r}")
 
 
if __name__ == "__main__":
    main()