Python 的 rstrip 参数是字符集,不是后缀
一个稳定复现、静默失效的字符串处理陷阱,以及正确的后缀移除写法。
str.rstrip(chars) 的参数是字符集,不是后缀字符串。它删除字符串右侧所有属于该字符集的字符。
"capacitor-aluminum".rstrip(".html")
这不是删掉 .html,而是删掉右侧所有 . / h / t / m / l → "capacitor-aluminu"(末尾 m 被误删)。
真实事故
某次 slug 处理里出现三个稳定错误:
capacitor-aluminum→capacitor-aluminu(丢 m)nvram→nvra(丢 m)capacitor-film→capacitor-fi(丢 lm)
这类错误在 URL / slug 处理里极易隐蔽发生,而且是稳定的——同样输入总是同样错误输出,让去重键和 URL 构造静默失效。不会报错,只会得到错误数据。
正确写法
移除后缀用显式切片:
if s.endswith(".html"):
s = s[:-len(".html")]
或 Python 3.9+:
s = s.removesuffix(".html")
排查习惯
审查任何 .rstrip("...") / .strip("...") 调用,先确认意图是字符集还是后缀。如果是后缀,一律换成 removesuffix。这个替换没有副作用,值得全局做。