为什么codecs.iterdecode()吃空字符串?

Che*_*ian 5 python unicode utf-8 codec python-2.7

为什么以下两种解码方法会返回不同的结果?

>>> import codecs
>>>
>>> data = ['', '', 'a', '']
>>> list(codecs.iterdecode(data, 'utf-8'))
[u'a']
>>> [codecs.decode(i, 'utf-8') for i in data]
[u'', u'', u'a', u'']
Run Code Online (Sandbox Code Playgroud)

这是一个错误还是预期的行为?我的Python版本2.7.13.

use*_*ica 5

这是正常的。iterdecode在编码块上采用迭代器并在解码块上返回迭代器,但它不保证一对一的对应关系。它只保证所有输出块的串联是对所有输入块串联的有效解码。

如果您查看源代码,您会看到它明确丢弃了空输出块:

def iterdecode(iterator, encoding, errors='strict', **kwargs):
    """
    Decoding iterator.
    Decodes the input strings from the iterator using an IncrementalDecoder.
    errors and kwargs are passed through to the IncrementalDecoder
    constructor.
    """
    decoder = getincrementaldecoder(encoding)(errors, **kwargs)
    for input in iterator:
        output = decoder.decode(input)
        if output:
            yield output
    output = decoder.decode("", True)
    if output:
        yield output
Run Code Online (Sandbox Code Playgroud)

请注意,原因iterdecode存在,并且您不会decode自己调用所有块的原因是解码过程是有状态的。一个字符的 UTF-8 编码形式可能被分成多个块。其他编解码器可能具有非常奇怪的状态行为,例如可能会反转所有字符的大小写的字节序列,直到您再次看到该字节序列。