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

Why codecs.iterdecode() eats empty strings?

为什么下面两种解码方式return结果不同?

>>> 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'']

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

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

如果您查看 source code,您会发现它明确丢弃了空输出块:

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

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