Python 精确删除前后缀:removeprefix、removesuffix 与 strip 的边界

10-22 5阅读

处理文件名或业务键时,“删除开头、结尾的一段固定文字”很容易被写成 lstrip 或 rstrip。问题常常藏在正文碰巧包含相同字母的地方:扩展名看似去掉了,真正的名字也少了一截。本文只讨论基础 str 的精确前后缀删除,不把它扩展成字符串 API 清单。

Python 精确删除前后缀:removeprefix、removesuffix 与 strip 的边界
独立模型生成的概念示意图,非软件截图。上排移除一份完整前缀,下排按字符集合持续剥离。

一、删除的是完整片段,还是字符集合?

Python 3.9 起提供 removeprefix 与 removesuffix。前者只在左边界匹配完整前缀,后者只在右边界匹配完整后缀。lstrip、rstrip 则把参数看成字符集合,从指定一端连续移除集合成员,遇到不在集合中的字符才停下。依据见 官方字符串文档。

下面的 report.txt 是一个很实用的反例:rstrip 的集合含有点、t、x,它移除扩展名后,还会继续移除 report 的最后一个 t。需要固定标记时,直接表达完整前后缀,避免让“数据刚好没撞上”掩盖错误。

filename = "report.txt"
print(filename.removesuffix(".txt"))  # report
print(filename.rstrip(".txt"))        # repor

key = "pre:pre:item"
print(key.removeprefix("pre:"))       # pre:item
print("xpre:item".removeprefix("pre:"))  # xpre:item
print("abc".removesuffix(""))          # abc
print("abc".removesuffix("abc"))       # 空串

# 文件名模式明确时,删除的是指定文本,而不是解析文件类型。
name = "backup.tar.gz"
print(name.removesuffix(".gz"))       # backup.tar
print(name.removesuffix(".tar.gz"))   # backup

二、只删除一次,空后缀也有意义

pre:pre:item 调用一次 removeprefix 后留下 pre:item;重复调用或循环删除,是另一项业务规则。没有匹配时保留原内容,参数等于整个输入时得到空串。返回内容相等用 == 判断,不要用 is 推测是否删除成功;本文也不承诺创建了新对象。

空前缀、空后缀均不改变内容。手写后缀删除时尤其容易漏掉保护条件:len("") 是零,负零仍是零,text[:-0] 因而是空串。PEP 616 特别处理了这个边界。理解等价切片有助于排错,但业务代码优先用内置方法。

# 仅演示基础str的内容语义,不承诺对象身份或子类行为。
def remove_suffix_once(text, suffix):
    if suffix and text.endswith(suffix):
        return text[:-len(suffix)]
    return text

print(remove_suffix_once("abc", ""))       # abc
print(remove_suffix_once("x.tar.tar", ".tar"))  # x.tar
print("abc"[:-0])                          # 空串

另外,removeprefix 不接受一组候选前缀元组,str 的 removesuffix 也不能直接接收 bytes。若需求是多种标记,先定义匹配顺序、大小写规则及是否允许连续删除,再单独实现,不要把 startswith 的参数能力照搬过来。

三、看起来一样,不代表码点相同

这些方法不会自动折叠大小写,也不会做 Unicode 规范化。一个预组合的 é,与 e 加组合重音可能外观相同,却是不同的码点序列。只删除后者开头的 e,会留下重音;对复合表情删除首个码点,也可能留下连接符。因此它们不是按“一个可见字符”裁切的工具。Unicode 背景见 官方 Unicode HOWTO。

text = "e\u0301clair"
print(ascii(text.removeprefix("é")))        # 'e\u0301clair'
print(ascii(text.removeprefix("e\u0301")))  # 'clair'
print(ascii(text.removeprefix("e")))        # '\u0301clair'
print("IMG:item".removeprefix("img:"))     # IMG:item

# 精确移除LF时,CR仍然保留。
print(repr("row\r\n".removesuffix("\n")))  # 'row\r'

规范化、大小写无关匹配当然可以是合理需求,但那会改变本文的精确匹配契约。不要先在转换后的文本上判断,再随意沿用原文本长度切片。日志换行也类似:只移除 LF,并不等于去掉一个完整 CRLF。

四、把边界写进可复现测试

以下套件包含 44 条正常或异常用例,以及 8 个刻意写错的封装。每条预期先按契约独立推导并冻结,再编写和运行套件;没有用被测方法生成答案。反例分别捕捉字符集合替代、全局替换、非边界替换、空后缀切片、重复删除,以及擅自大小写折叠或规范化。

首轮在 CPython 3.12.14 与 3.13.5 的普通、-O 模式下均为 0 失败,四轮都识别全部 8 个反例;没有修改预期,也没有隐藏失败后重跑。校验使用显式条件,不依赖优化模式可能移除的 assert。这是有限输入的本地回归测试,不是性能比较或模型能力评测。

完整复制下一块为 suite.py,以 UTF-8 保存,运行 python suite.py 或 python -O suite.py。预期数据已经内嵌,无需另下载文件;每行最后一列说明该案例的推理依据。正常结尾应显示 44 cases、8 wrong-wrapper witnesses 与 failures= 0。故意错误的函数仅用于反例,不应复制进业务实现。

完整可运行套件:冻结预期、44 条用例与 8 个错误封装反例
import hashlib
import json
import platform
import sys
import unicodedata

# Frozen before implementation; each row carries its independent reason.
ORACLE_JSON = r'''{
  "cases": [
    ["P01", "removeprefix", "img:cover", "img:", "cover", "完整前缀位于左边界"],
    ["P02", "removeprefix", "ximg:cover", "img:", "ximg:cover", "前缀不在左边界"],
    ["P03", "removeprefix", "pre:pre:item", "pre:", "pre:item", "重复前缀只删除一份"],
    ["P04", "removeprefix", "xpre:item", "pre:", "xpre:item", "内部出现不删除"],
    ["P05", "removeprefix", "abc", "", "abc", "空前缀不改变内容"],
    ["P06", "removeprefix", "abc", "abc", "", "前缀等于整个输入"],
    ["P07", "removeprefix", "", "x", "", "空输入不匹配非空前缀"],
    ["P08", "removeprefix", "", "", "", "空输入和空前缀"],
    ["P09", "removeprefix", "ab", "abc", "ab", "前缀更长无法匹配"],
    ["P10", "removeprefix", "IMG:x", "img:", "IMG:x", "大小写不同不匹配"],
    ["P11", "removeprefix", "编号:云鹊", "编号:", "云鹊", "中文完整码点序列可匹配"],
    ["P12", "removeprefix", "\u0000tag", "\u0000", "tag", "空字符是普通码点"],
    ["P13", "removeprefix", "e\u0301clair", "é", "e\u0301clair", "不自动做规范化"],
    ["P14", "removeprefix", "e\u0301clair", "e\u0301", "clair", "相同组合序列可匹配"],
    ["P15", "removeprefix", "e\u0301clair", "e", "\u0301clair", "可在组合字符内部切开"],
    ["P16", "removeprefix", "👩\u200d💻log", "👩", "\u200d💻log", "不保护表情字素簇边界"],
    ["S01", "removesuffix", "notes.md", ".md", "notes", "完整后缀位于右边界"],
    ["S02", "removesuffix", "notes.md.tmp", ".md", "notes.md.tmp", "后缀不在右边界"],
    ["S03", "removesuffix", "x.tar.tar", ".tar", "x.tar", "重复后缀只删除一份"],
    ["S04", "removesuffix", "a.md.b", ".md", "a.md.b", "中间扩展名不删除"],
    ["S05", "removesuffix", "abc", "", "abc", "空后缀保留内容"],
    ["S06", "removesuffix", "abc", "abc", "", "后缀等于整个输入"],
    ["S07", "removesuffix", "", "x", "", "空输入不匹配非空后缀"],
    ["S08", "removesuffix", "", "", "", "空输入和空后缀"],
    ["S09", "removesuffix", "ab", "cab", "ab", "后缀更长无法匹配"],
    ["S10", "removesuffix", "x.TXT", ".txt", "x.TXT", "后缀也区分大小写"],
    ["S11", "removesuffix", "云鹊(草稿)", "(草稿)", "云鹊", "中文完整后缀"],
    ["S12", "removesuffix", "row\n\n", "\n", "row\n", "只移除一个换行"],
    ["S13", "removesuffix", "row\r\n", "\n", "row\r", "移除LF不会自动移除CR"],
    ["S14", "removesuffix", "cafe\u0301", "\u0301", "cafe", "可单独移除组合重音"],
    ["S15", "removesuffix", "café", "e\u0301", "café", "视觉近似不等于码点相等"],
    ["L01", "lstrip", "txt_report", "txt_", "report", "字符集合连续剥离左侧"],
    ["L02", "lstrip", "abba-core", "ab", "-core", "集合不保留子串顺序"],
    ["P17", "removeprefix", "abba-core", "ab", "ba-core", "精确前缀只移除ab"],
    ["R01", "rstrip", "report.txt", ".txt", "repor", "集合会继续吃掉正文末尾t"],
    ["R02", "rstrip", "report.tx", ".txt", "repor", "无需出现完整txt后缀"],
    ["L03", "lstrip", "babaX", "ab", "X", "不同排列也属于字符集合"],
    ["R03", "rstrip", "Xabab", "ab", "X", "集合重复剥离到边界"],
    ["L04", "lstrip", " abc", "", " abc", "空集合不会剥离空白"],
    ["R04", "rstrip", "abc ", "", "abc ", "右侧空集合也不处理空白"],
    ["E01", "removeprefix", "abc", {"tuple": ["a", "b"]}, {"error": "TypeError"}, "不接受候选前缀元组"],
    ["E02", "removesuffix", "abc", {"bytes": "c"}, {"error": "TypeError"}, "str后缀不接受bytes"],
    ["L05", "lstrip", " \tx", null, "x", "None使用空白字符规则"],
    ["R05", "rstrip", "x \t", null, "x", "右侧None也使用空白规则"]
  ],
  "witnesses": [
    ["W01", "prefix_as_set", "removeprefix", "abba-core", "ab", "ba-core", "-core", "lstrip会多删ba"],
    ["W02", "suffix_as_set", "removesuffix", "report.txt", ".txt", "report", "repor", "rstrip会多删正文t"],
    ["W03", "replace_everywhere", "removeprefix", "pre:core:pre:", "pre:", "core:pre:", "core:", "全局replace损坏后面的同名内容"],
    ["W04", "replace_first", "removeprefix", "xpre:core", "pre:", "xpre:core", "xcore", "replace一次仍不检查边界"],
    ["W05", "slice_empty_suffix", "removesuffix", "abc", "", "abc", "", "负零切片得到空串"],
    ["W06", "repeat_prefix", "removeprefix", "pre:pre:item", "pre:", "pre:item", "item", "循环删除改变只删一份的约定"],
    ["W07", "casefold_prefix", "removeprefix", "IMG:item", "img:", "IMG:item", "item", "大小写折叠改变精确匹配约定"],
    ["W08", "normalize_prefix", "removeprefix", "e\u0301clair", "é", "e\u0301clair", "clair", "规范化改变原始码点约定"]
  ]
}
'''

DATA = json.loads(ORACLE_JSON)
EXPECTED_SHA256 = "2b4fe0e6368cee018e3db6f228c9ad3861df2355d0eb2e9b302bedd0cd29e8ce"
if hashlib.sha256(ORACLE_JSON.encode("utf-8")).hexdigest() != EXPECTED_SHA256:
    raise RuntimeError("Frozen oracle content changed")


def unpack(value):
    if isinstance(value, dict) and "tuple" in value:
        return tuple(value["tuple"])
    if isinstance(value, dict) and "bytes" in value:
        return value["bytes"].encode("ascii")
    return value


# Intentionally incorrect wrappers for the exact-affix contract.
def prefix_as_set(text, affix):
    return text.lstrip(affix)


def suffix_as_set(text, affix):
    return text.rstrip(affix)


def replace_everywhere(text, affix):
    return text.replace(affix, "")


def replace_first(text, affix):
    return text.replace(affix, "", 1)


def slice_empty_suffix(text, affix):
    return text[:-len(affix)] if text.endswith(affix) else text


def repeat_prefix(text, affix):
    while affix and text.startswith(affix):
        text = text[len(affix):]
    return text


def casefold_prefix(text, affix):
    if text.casefold().startswith(affix.casefold()):
        return text[len(affix):]
    return text


def normalize_prefix(text, affix):
    return unicodedata.normalize("NFC", text).removeprefix(
        unicodedata.normalize("NFC", affix)
    )


WRONG = {
    "prefix_as_set": prefix_as_set,
    "suffix_as_set": suffix_as_set,
    "replace_everywhere": replace_everywhere,
    "replace_first": replace_first,
    "slice_empty_suffix": slice_empty_suffix,
    "repeat_prefix": repeat_prefix,
    "casefold_prefix": casefold_prefix,
    "normalize_prefix": normalize_prefix,
}


def main():
    failures = []
    print("Python", platform.python_version(), platform.python_implementation(),
          "optimize=", sys.flags.optimize)
    print("oracle_sha256=", EXPECTED_SHA256)
    for case_id, method, text, raw_arg, expected, reason in DATA["cases"]:
        try:
            actual = getattr(text, method)(unpack(raw_arg))
        except Exception as error:
            actual = {"error": type(error).__name__}
        if actual != expected:
            failures.append(case_id)
            print("FAIL", case_id, "got", repr(actual), "expected", repr(expected))
        else:
            print("PASS", case_id, reason)
    for case_id, name, method, text, affix, correct, wrong, reason in DATA["witnesses"]:
        try:
            actual_correct = getattr(text, method)(affix)
            actual_wrong = WRONG[name](text, affix)
            ok = actual_correct == correct and actual_wrong == wrong and wrong != correct
        except Exception as error:
            ok = False
            actual_correct = "unexpected exception"
            actual_wrong = repr(error)
        if not ok:
            failures.append(case_id)
            print("FAIL", case_id, repr(actual_correct), repr(actual_wrong))
        else:
            print("WITNESS", case_id, repr(correct), "!=", repr(wrong), reason)
    print("SUMMARY", len(DATA["cases"]), "cases;", len(DATA["witnesses"]),
          "wrong-wrapper witnesses; failures=", len(failures))
    if failures:
        raise SystemExit(1)


if __name__ == "__main__":
    main()

最后用一句话选 API:需求若是“这一整段固定文字”,用 removeprefix 或 removesuffix;需求若是“边缘连续出现的这些字符”,再用 lstrip 或 rstrip。把空串、重复标记与 Unicode 形式写进输入契约,比事后猜测字符串为什么变短更可靠。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。