Python partition 与 rpartition:精确分隔、缺失结果和 40 个边界测试

10-22 5阅读

处理“键=值”、带前缀的标签或自定义文本记录时,经常只想切开一个边界,同时知道边界是否真的存在。Python 的 partition 和 rpartition 正好返回“左侧、命中的分隔符、右侧”三项。它们不会替你理解配置文件语法,但能让一次切分的结果更明确。本文以可复跑实验解释边界条件,不作速度或安全性比较。

Python partition 与 rpartition:精确分隔、缺失结果和 40 个边界测试

配图为独立模型生成的概念示意图,不是解释器截图。测试环境是 CPython 3.12.14;文档于北京时间 2026 年 10 月 22 日核验,文档页面版本与本地运行版本并不等同。

一、先看中间项,再判断空值

对同一个输入,partition 选择最靠左的匹配,rpartition 选择最靠右的匹配。返回顺序始终是左、中、右,不会因为搜索方向改变就把结果倒过来。没有匹配时,两者的原文位置不同:partition 把原文放在第一项,rpartition 把原文放在第三项。这个不对称约定见于 partition 官方说明和 rpartition 官方说明。

实际读取“key=”时,右侧为空并不表示缺少等号。应先把结果解包为 left、mark、right,再检查 mark。对于这里的非空精确分隔符,mark 非空表示匹配成功;是否允许空键、空值,则由业务另行判断。“=value”和“=”同样可以成功切分。不要只检查 left 或 right 的真假,否则合法的边界空字段会被混同为失败。

反过来,“plain”没有等号,两种方法都会留下空的中间项。若你希望无分隔符时保留整个标题作为左侧,partition 的回退形状较顺手;若想从文件标签尾部拆出最后一段,可考虑 rpartition,但仍要显式处理未找到的分支。

二、分隔符是完整文本,不是空白规则

传入多个字符时,它们共同组成一个完整分隔符。测试中的尖括号对只有连续出现才算命中,不表示“遇到任一括号就切”。连续分隔符也不会自动合并:在双冒号文本中按单冒号切一次,剩下的冒号仍留在某一侧。

空格尤其容易造成误判。按一个普通空格切分,会保留其余空格;制表符、换行符、不换行空格不会自动等价于这个普通空格。只有把对应字符本身作为分隔符才会命中。下面的 repr 输出特意显示引号和转义符,避免肉眼看不清尾部空白。

这与 split 不指定分隔符的空白拆分模式不同,后者有合并连续空白的规则,详见 split 文档。partition 不能通过传入 None 获得那套规则。本次测试中,None 和文本/字节混用产生 TypeError,空字符串或空字节分隔符产生 ValueError。测试只比较异常类型,不绑定异常提示的具体措辞。

三、重叠匹配与 Unicode 都要按实际序列理解

“ababa”里,“aba”从索引 0 和索引 2 开始都能匹配。partition 取前者,得到空左侧与“ba”;rpartition 取后者,得到“ab”与空右侧。不要先从左边枚举不重叠匹配再拿最后一个,那会遗漏索引 2。本例的 nonoverlap-last 错误版本专门验证这个区别。

中文也可作为分隔符,但精确匹配不等于视觉近似匹配。测试把预组合的 é 与 e 加组合重音分开表示:前者不会命中后者的码点序列,而完整的 e 加重音可以命中。大小写不同的 X 与 x 也不互换。需要 Unicode 规范化时,应把它作为输入处理规则明确设计,不能默默塞进切分函数。本例引入 NFC 只用于构造一个故意错误的变体;规范化函数的定义见 官方文档。

四、bytes 类似,但别抹掉类型边界

当源与分隔符都为 bytes 时,本例得到三个 bytes 项;未找到时保留原文的位置和 str 一致。它按字节序列工作,不需要先把输入当成 UTF-8 解码。测试包含零字节及非 UTF-8 字节,用来防止封装层擅自解码或转换类型。

bytes 文档允许 bytes-like 分隔符。一个容易漏掉的细节是:本次 CPython 3.12.14 实测,命中 bytearray 或 memoryview 分隔符时,中间项分别保留对应类型,左右项仍为 bytes。不要由普通 bytes 示例推出“任何分隔符都会返回三个 bytes”。这里检查值和类型,不对对象身份或所有 Python 实现作额外保证;生产代码若仅需 bytes,明确限定接口类型通常更容易理解。

五、完整示例与固定预期

把以下三个代码块分别保存为 demo.py、oracle.py、tests.py,放在同一个目录,用 UTF-8 保存。不需要第三方包。运行 python demo.py 查看示例,再运行 python tests.py 和 python -O tests.py 做两轮检查。

预期表由规则手工写出,并先于示例和测试器初次冻结。初跑暴露了两个预期错误:把 bytes-like 分隔符的中间项一律写成了 bytes。依据官方“分隔符本身”的描述,已修正这两个类型预期并重新固定,其他 38 项和示例输出未改。下方发布的是修正版,不声称预期从未调整,也不使用被测函数动态生成答案。

demo.py

"""Run with python demo.py; no third-party dependencies."""
def cut(method, source, separator):
    if method not in ('partition', 'rpartition'):
        raise ValueError('unsupported method')
    return getattr(source, method)(separator)


def main():
    examples = (
        ('first', 'partition', 'key=value=extra', '='),
        ('last', 'rpartition', 'key=value=extra', '='),
        ('missing-left', 'partition', 'plain', '='),
        ('missing-right', 'rpartition', 'plain', '='),
        ('empty-value', 'partition', 'key=', '='),
        ('keep-spaces', 'partition', ' key = value ', '='),
        ('overlap-last', 'rpartition', 'ababa', 'aba'),
        ('raw-bytes', 'partition', b'\xff=\x80', b'='),
    )
    for label, method, source, separator in examples:
        print(f'{label}: {cut(method, source, separator)!r}')


if __name__ == '__main__':
    main()

demo.py 的预期输出

first: ('key', '=', 'value=extra')
last: ('key=value', '=', 'extra')
missing-left: ('plain', '', '')
missing-right: ('', '', 'plain')
empty-value: ('key', '=', '')
keep-spaces: (' key ', '=', ' value ')
overlap-last: ('ab', 'aba', '')
raw-bytes: (b'\xff', b'=', b'\x80')

oracle.py

"""Hand-derived fixed expectations; two buffer-type corrections are documented."""
CASES = (
    ('first', 'partition', 'a=b=c', '=', ('a', '=', 'b=c')),
    ('last', 'rpartition', 'a=b=c', '=', ('a=b', '=', 'c')),
    ('missing-left', 'partition', 'abc', '=', ('abc', '', '')),
    ('missing-right', 'rpartition', 'abc', '=', ('', '', 'abc')),
    ('leading', 'partition', '=value', '=', ('', '=', 'value')),
    ('trailing', 'rpartition', 'key=', '=', ('key', '=', '')),
    ('only-separator', 'partition', '=', '=', ('', '=', '')),
    ('empty-left', 'partition', '', ':', ('', '', '')),
    ('empty-right', 'rpartition', '', ':', ('', '', '')),
    ('whole-delimiter', 'partition', 'a<>b<>c', '<>', ('a', '<>', 'b<>c')),
    ('not-character-set', 'partition', 'a>b<c', '<>', ('a>b<c', '', '')),
    ('consecutive-first', 'partition', 'a::b', ':', ('a', ':', ':b')),
    ('consecutive-last', 'rpartition', 'a::b', ':', ('a:', ':', 'b')),
    ('spaces-first', 'partition', ' a  b ', ' ', ('', ' ', 'a  b ')),
    ('spaces-last', 'rpartition', ' a  b ', ' ', (' a  b', ' ', '')),
    ('tab-not-space', 'partition', 'a\tb', ' ', ('a\tb', '', '')),
    ('newline-literal', 'partition', 'a\nb\n', '\n', ('a', '\n', 'b\n')),
    ('nbsp-not-space', 'partition', 'a\u00a0b', ' ', ('a\u00a0b', '', '')),
    ('chinese', 'rpartition', '甲界乙界丙', '界', ('甲界乙', '界', '丙')),
    ('case-sensitive', 'partition', 'aXb', 'x', ('aXb', '', '')),
    ('no-normalization', 'partition', 'cafe\u0301:end', '\u00e9', ('cafe\u0301:end', '', '')),
    ('combining-exact', 'partition', 'cafe\u0301:end', 'e\u0301', ('caf', 'e\u0301', ':end')),
    ('overlap-first', 'partition', 'ababa', 'aba', ('', 'aba', 'ba')),
    ('overlap-last', 'rpartition', 'ababa', 'aba', ('ab', 'aba', '')),
    ('separator-longer', 'rpartition', 'ab', 'abc', ('', '', 'ab')),
    ('empty-sep-left', 'partition', 'abc', '', ValueError),
    ('empty-sep-right', 'rpartition', 'abc', '', ValueError),
    ('none-is-not-default', 'partition', 'a b', None, TypeError),
    ('bytes-reject-text', 'partition', b'a=b', '=', TypeError),
    ('text-reject-bytes', 'partition', 'a=b', b'=', TypeError),
    ('bytes-first', 'partition', b'a=b=c', b'=', (b'a', b'=', b'b=c')),
    ('bytes-last', 'rpartition', b'a=b=c', b'=', (b'a=b', b'=', b'c')),
    ('bytes-missing-left', 'partition', b'abc', b'=', (b'abc', b'', b'')),
    ('bytes-missing-right', 'rpartition', b'abc', b'=', (b'', b'', b'abc')),
    ('bytes-overlap', 'rpartition', b'ababa', b'aba', (b'ab', b'aba', b'')),
    ('nul-separator', 'partition', b'a\x00b', b'\x00', (b'a', b'\x00', b'b')),
    ('bytes-empty-sep', 'partition', b'abc', b'', ValueError),
    ('bytearray-separator', 'partition', b'a:b', bytearray(b':'), (b'a', bytearray(b':'), b'b')),
    ('memoryview-separator', 'rpartition', b'a:b:c', memoryview(b':'), (b'a:b', memoryview(b':'), b'c')),
    ('raw-bytes', 'partition', b'\xff=\x80', b'=', (b'\xff', b'=', b'\x80')),
)

GOLDEN = """first: ('key', '=', 'value=extra')
last: ('key=value', '=', 'extra')
missing-left: ('plain', '', '')
missing-right: ('', '', 'plain')
empty-value: ('key', '=', '')
keep-spaces: (' key ', '=', ' value ')
overlap-last: ('ab', 'aba', '')
raw-bytes: (b'\\xff', b'=', b'\\x80')"""

EXPECTED_REPORT = """oracle: 40/40 passed
mutants: 10/10 rejected
golden: exact, optional one terminal LF
PASS"""

tests.py

"""Fixed-oracle tests and deliberately incorrect semantic variants."""
import contextlib
import io
import unicodedata
from demo import cut, main
from oracle import CASES, GOLDEN, EXPECTED_REPORT


def same(actual, expected):
    if type(actual) is not type(expected):
        return False
    if isinstance(expected, tuple):
        return len(actual) == len(expected) and all(
            same(a, b) for a, b in zip(actual, expected)
        )
    return actual == expected


def outcome(function, case):
    _, method, source, separator, _ = case
    try:
        return ('value', function(method, source, separator))
    except Exception as error:
        return ('error', type(error))


def expected(case):
    value = case[4]
    if isinstance(value, type) and issubclass(value, Exception):
        return ('error', value)
    return ('value', value)


def mismatches(function):
    return [case[0] for case in CASES
            if not same(outcome(function, case), expected(case))]


def mutant(name, method, source, separator):
    empty = source[:0]
    if name == 'allow-empty' and separator == empty:
        return (source, empty, empty)
    if name == 'coerce-types':
        if isinstance(source, str) and isinstance(separator, bytes):
            separator = separator.decode('ascii')
        elif isinstance(source, bytes) and isinstance(separator, str):
            separator = separator.encode('ascii')
        elif separator is None:
            separator = ' '
    if name == 'swap-direction':
        method = 'rpartition' if method == 'partition' else 'partition'
    if name == 'normalize-text' and isinstance(source, str) and isinstance(separator, str):
        source = unicodedata.normalize('NFC', source)
        separator = unicodedata.normalize('NFC', separator)
    result = cut(method, source, separator)
    left, middle, right = result
    if name == 'missing-left' and not middle:
        return (source, empty, empty)
    if name == 'missing-right' and not middle:
        return (empty, empty, source)
    if name == 'drop-delimiter':
        return (left, empty, right)
    if name == 'whitespace-collapse' and separator == ' ':
        parts = source.split(None, 1)
        if len(parts) == 2:
            return (parts[0], ' ', parts[1])
    if name == 'delimiter-character-set' and isinstance(source, str) and len(separator) > 1:
        positions = [i for i, char in enumerate(source) if char in separator]
        if positions:
            index = positions[0] if method == 'partition' else positions[-1]
            return (source[:index], source[index:index + 1], source[index + 1:])
    if name == 'nonoverlap-last' and method == 'rpartition':
        positions = []
        index = source.find(separator)
        while index >= 0:
            positions.append(index)
            index = source.find(separator, index + len(separator))
        if positions:
            index = positions[-1]
            return (source[:index], separator, source[index + len(separator):])
    return result


MUTANTS = (
    'swap-direction', 'missing-left', 'missing-right', 'drop-delimiter',
    'whitespace-collapse', 'delimiter-character-set', 'normalize-text',
    'allow-empty', 'coerce-types', 'nonoverlap-last',
)


def exact_text(actual, golden):
    # Accept the frozen text or precisely one added terminal LF, nothing else.
    return actual == golden or actual == golden + '\n'


def run():
    if len(CASES) != 40 or len({case[0] for case in CASES}) != 40:
        raise RuntimeError('oracle count or identifiers changed')
    failures = mismatches(cut)
    if failures:
        raise RuntimeError(f'baseline failed: {failures}')
    for name in MUTANTS:
        failed = mismatches(lambda m, s, d: mutant(name, m, s, d))
        if not failed:
            raise RuntimeError(f'mutant survived: {name}')
    output = io.StringIO()
    with contextlib.redirect_stdout(output):
        main()
    if not exact_text(output.getvalue(), GOLDEN):
        raise RuntimeError(f'demo output changed: {output.getvalue()!r}')
    for altered in (GOLDEN + ' ', GOLDEN + '\n\n', ' ' + GOLDEN):
        if exact_text(altered, GOLDEN):
            raise RuntimeError('golden comparator ignores significant whitespace')
    report = '\n'.join((
        f'oracle: {len(CASES)}/{len(CASES)} passed',
        f'mutants: {len(MUTANTS)}/{len(MUTANTS)} rejected',
        'golden: exact, optional one terminal LF',
        'PASS',
    ))
    if not exact_text(report, EXPECTED_REPORT):
        raise RuntimeError('report changed')
    print(report)


if __name__ == '__main__':
    run()

普通运行与 -O 运行的预期输出

oracle: 40/40 passed
mutants: 10/10 rejected
golden: exact, optional one terminal LF
PASS

六、怎样读测试结果

40 个案例覆盖首尾命中、缺失、空字段、完整分隔符、空白、Unicode、重叠、异常和字节类型。same 同时比较结构、元素类型与值,因此不会因为 bytearray 与 bytes 内容相等就放过类型差异。10 个错误变体分别改坏方向、缺失回退、分隔符保留、空白处理、字符集合解释、规范化、空分隔符、类型转换和重叠处理;全部至少被一个案例拒绝,表示这些测试能识别所列错误,不表示穷尽所有缺陷。

校验器用显式条件和异常报告失败,没有把验证依赖在 assert 上;-O 会移除 assert 语句,因此两种模式都要跑。文本金标只接受原文或末尾额外一个换行,不调用 strip 抹掉有意义的空格。复制代码时也应保留缩进、转义符和空格。

选用这两个方法的判断很简单:若需求是“围绕一次精确边界取三项,并区分缺失和空值”,它们很合适。若输入还包含引号、转义、嵌套结构或多种语法规则,先明确语法,再选择对应解析方式,不要让一次字符串切分承担它没有承诺的工作。

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