语言核心第 3 章预计 18 分钟
本页目录(17 节)

03 · 数值、字符串、Unicode 与 bytes

学完这章,你能解释「为什么 len 和屏幕上看到的字不一样」「为什么读到中文就 UnicodeDecodeError」,并按场景选 float / Decimal / bytes。

本章目标

  • 能说明 int 任意精度、float 的 IEEE-754 误差,以及 Decimal 的适用边界
  • 能解释 str 是 Unicode 码点序列,len 数码点而不是字节或字素
  • 能处理 encode/decode 与 errors= 策略,读懂 UnicodeDecodeError
  • 能区分 bytes、bytearray、memoryview 的拷贝与共享语义
  • 能用 f-string/format spec 控制输出,并知道 repr 与 str 的差别

前置知识

  • 第 02 章(真值、名字绑定、运算符)
  • 了解字符编码的基本概念(UTF-8 是变长字节序列)

从你熟悉的语言出发

概念 C / C++ Go Java Python
整数 定宽,溢出回绕 定宽 定宽 + 溢出回绕 int 任意精度
浮点 double IEEE-754 float64 double float 也是 IEEE-754 double
十进制金额 自己实现/库 自己实现/库 BigDecimal decimal.Decimal
字符串 char* + 编码约定 UTF-8 string UTF-16 String Unicode 码点序列 str
字节序列 unsigned char[] []byte byte[] bytes / bytearray / memoryview

类比一:str 是「码点数组」,不是「字节数组」。 C 的 char* 本质是字节;Python 的 str 已经解码成 Unicode 码点。encode() 才是把它变成字节,decode() 是反向操作。把 str 当字节用,就会在中文、emoji 上出错。

类比二:Decimal 像 Java 的 BigDecimal,float 像 double。 金额、税率、精确小数用 Decimal;科学计算、图形、统计用 float。两者不能混算,Decimal("0.1") + 0.1 会抛 TypeError。

正文

3.1 int:任意精度,但有字符串转换上限

>>> 2**100
1267650600228229401496703205376
>>> (2**100).bit_length()
101

int 不会溢出,代价是大数运算变慢、内存变大。

从 3.11 起,int 与 str 互转有位数上限(默认 4300 位),防止超大整数的十进制转换拖垮服务:

>>> len(str(10**5000))
Traceback (most recent call last):
  ...
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

需要处理超大整数时,用 sys.set_int_max_str_digits() 显式放宽,并评估 CPU 成本。

3.2 float 与 Decimal

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False

float 是 IEEE-754 双精度,很多十进制小数无法精确表示。比较浮点结果用 math.isclose:

>>> import math
>>> math.isclose(0.1 + 0.2, 0.3)
True

金额/税率用 Decimal:

>>> from decimal import Decimal
>>> Decimal("0.1") + Decimal("0.2") == Decimal("0.3")
True

Decimal 的构造要用字符串,Decimal(0.1) 会把浮点误差带进去。Fraction 适合精确有理数(如 1/3),但日常业务少用。

3.3 str 是 Unicode 码点序列

>>> len("中文")
2
>>> len("中文".encode("utf-8"))
6
>>> "中文"[0]
'中'
  • len(str) 数码点;UTF-8 下中文通常 3 字节。
  • 索引/切片按码点,不按字节,也不会拆开代理对(Python 没有 UTF-16 代理对问题)。
  • 「用户看到的字」(字素簇)可能由多个码点组成,len 不等于视觉字符数。

规范化:

>>> a = "\u00e9"  # é 单码点
>>> b = "e\u0301"  # e + 组合重音
>>> a == b
False
>>> import unicodedata
>>> unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b)
True

比较用户输入、做用户名/搜索键时,先 NFC 规范化;大小写不敏感比较用 casefold(),它比 lower() 更彻底("ß".casefold() == "ss")。

3.4 encode / decode 与 errors=

>>> text = "中文"
>>> raw = text.encode("utf-8")
>>> raw
b'\xe4\xb8\xad\xe6\x96\x87'
>>> raw.decode("utf-8")
'中文'

常见编码:utf-8(默认)、utf-16、latin-1(单字节,常被误用)、ascii。读写文件时显式 encoding="utf-8",不要依赖平台默认(Windows 可能是 GBK/CP936)。

errors= 策略:

策略 行为 适用
strict(默认) 抛 UnicodeDecodeError 协议解析、数据完整性要求高
replace 插入 U+FFFD � 展示、日志容错
ignore 丢弃非法字节 只关心可解析部分
backslashreplace 转成 \xNN 文本 调试

3.5 bytes、bytearray、memoryview

>>> b"abc"[0]
97
>>> bytearray(b"abc")[0] = 90
>>> bytes(bytearray(b"abc"))
b'abc'
  • bytes 不可变;bytearray 可变;两者都是 0–255 的字节序列。
  • memoryview 是缓冲区视图,切片不复制:
>>> buf = bytearray(b"abcdef")
>>> view = memoryview(buf)[1:4]
>>> buf[1] = ord("Z")
>>> bytes(view)
b'Zcd'

memoryview 适合大二进制解析、零拷贝切片;注意视图会随底层缓冲区变化。

str 与 bytes 不能直接拼接:

>>> "a" + b"b"
Traceback (most recent call last):
  ...
TypeError: can only concatenate str (not "bytes") to str

3.6 f-string、format 与 repr

>>> x, y = 3, 4
>>> f"{x:>3} + {y:<3} = {x + y:03d}"
'  3 + 4   = 007'
  • >/</^ 对齐,数字是宽度。
  • .2f 保留两位小数;03d 补零;, 千分位;% 百分比。
  • !r 用 repr,!s 用 str。
>>> repr("a")
"'a'"
>>> str("a")
'a'
>>> repr(0.1)
'0.1'

调试时用 repr,它保留引号/转义,能看出字符串边界。f-string 在 3.12 支持嵌套引号与多行表达式(PEP 701)。

报错现场

Traceback (most recent call last):
  File "/tmp/decode_demo.py", line 2, in <module>
    text = raw.decode("utf-8")
           ^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 3-4: unexpected end of data

逐行读:

  • line 2:raw 是 "中文".encode("utf-8")[:-1],被截掉最后一个字节。
  • ^^^^ 指向 decode 调用(3.11+ 精细定位)。
  • position 3-4:第 4 个字节开始是一个 3 字节字符,但只剩 2 字节,序列不完整。
  • unexpected end of data:不是「非法字节」,而是「数据不够」。

三种修法:

  1. 不要截断字节:按字符边界切分(先 decode 再切片,或按 UTF-8 结构解析)。
  2. 容错解码:raw.decode("utf-8", errors="replace"),接受 �。
  3. 按二进制处理:如果只是转发/存储,保持 bytes,不要 decode。

错误地选 latin-1 也能「解码成功」,但会得到乱码——它把每个字节映射成一个码点,不校验 UTF-8 结构。这是最危险的「假修复」。

反直觉差异:len 不是「字数」

你的直觉:len("👨‍👩‍👧") 应该是 1,因为屏幕上就是一个家庭表情;len("中文") 应该是 6,因为有 6 个字节。

实际行为:len(str) 数 Unicode 码点:

>>> len("👨‍👩‍👧")
5
>>> len("中文")
2
>>> len("中文".encode("utf-8"))
6

家庭 emoji 由「男人 + ZWJ + 女人 + ZWJ + 女孩」5 个码点组成;ß.upper() 是 SS,长度从 1 变 2。

为什么这样设计:str 的索引必须是 O(1) 的码点访问;如果按字素簇存储,需要额外索引结构,且 Unicode 字素规则会随版本变化。Python 选择「码点序列」这个稳定、简单的模型,把「显示宽度/字素」留给 unicodedata、终端或第三方库。

正确写法:

  • 需要字节长度:len(s.encode("utf-8"))。
  • 需要显示宽度:用 unicodedata.east_asian_width 或专用库,不要用 len。
  • 需要按「用户字符」切分:用字素簇库(本教程不引入),或明确限制输入为单码点。
  • 比较/索引前先 NFC 规范化。

性能与复杂度

操作 复杂度 实测(3.12.9 / macOS arm64) 说明
"".join(parts)(1 万段) O(n) 20.8 µs 一次性分配
s += p 循环(1 万段) O(n²) 最坏 210.4 µs 反复扩容;CPython 有优化但不保证
f-string f"{x}:{y}" O(输出长度) 56.1 ns 编译期拆成字节码拼接
% 格式化 O(输出长度) 56.5 ns 与 f-string 同量级
str.format O(输出长度) 76.2 ns 多一次方法查找/解析

测量命令:timeit.timeit,重复 20–100 万次。拼接必须用 join 或 f-string;循环 += 在数据量大时明显变慢。

示例索引

目录 演示什么 预期看到
examples/03-numbers-strings-unicode/01-float-vs-decimal/ 浮点误差与 Decimal 0.30000000000000004、False、Decimal: 0.3
examples/03-numbers-strings-unicode/02-unicode-normalization/ NFC 与码点长度 raw_equal: False、family_len: 5
examples/03-numbers-strings-unicode/03-encode-decode-errors/ UTF-8 截断与 errors b'\xe4...'、'中�'、'中'
examples/03-numbers-strings-unicode/04-bytes-vs-str/ 类型隔离与 memoryview TypeError、b'Zcd'

练习题

  1. 实现 safe_decode(data, errors="strict"),只允许三种策略,未知策略抛 ValueError。
  2. 实现 normalize_text(text):去空白 → NFC → casefold。
  3. 实现 close_enough(a, b, rel_tol=1e-9),用相对误差比较浮点数。
  1. 先检查 errors in {"strict", "replace", "ignore"},再 data.decode("utf-8", errors=errors)。非法字节在 strict 下会抛 UnicodeDecodeError,不要吞掉。
  2. unicodedata.normalize("NFC", text.strip()).casefold();casefold 处理 ß → ss。
  3. math.isclose(a, b, rel_tol=rel_tol, abs_tol=0.0);不要用 abs(a-b) < 1e-9,那在大数上不成立。

章末自检

  1. int 会溢出吗?从字符串转超大整数有什么限制?
  2. 0.1 + 0.2 == 0.3 为什么是 False?该用什么比较?
  3. len("中文") 与 len("中文".encode()) 分别是多少?为什么?
  4. NFC 与 NFD 的区别?什么时候必须规范化?
  5. errors="replace" 与 "ignore" 的差别?各自适合什么场景?
  6. memoryview 切片会复制吗?修改底层缓冲区会怎样?
  7. 为什么循环里用 s += p 拼接大量字符串不好?
  1. 不会;3.11+ 默认 4300 位上限,可 sys.set_int_max_str_digits 调整。
  2. 二进制浮点无法精确表示 0.3;用 math.isclose 或 Decimal。
  3. 2 与 6;str 数码点,UTF-8 中文 3 字节。
  4. NFC 组合、NFD 分解;比较用户输入、搜索键、跨系统数据时先规范化。
  5. replace 插入 �,ignore 丢弃;前者保留位置感,后者只留可解析部分。
  6. 不复制;底层变则视图变。
  7. 字符串不可变,每次 += 可能重新分配并复制,整体 O(n²)。

延伸阅读

  • The Python Tutorial §3.1.2 Strings、§7.1 Fancier Output Formatting
  • The Python Standard Library §4.8 str methods、§8.3 decimal、§9.2 unicodedata
  • Unicode Standard Annex #15 Unicode Normalization Forms
  • PEP 701 Syntactic formalization of f-strings
  • Python 3.11 Release Notes:Integer string conversion length limitation