连接字符串列表时出错

2024-04-19 18:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个应用程序中,我从另一个进程获得一个字典。此词典有一些非ascii字符,如Ä。你知道吗

我想从这个字典中生成一个json字符串,但我得到的只是

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)

因此,我启动了一个pudb会话并进入代码,直到找到抛出异常的行。你知道吗

在我的python版本(2.7.9,anaconda build)中,JSONEncoder类,encode函数。你知道吗

def encode(self, o):
    ...
    chunks = self.iterencode(o, _one_shot=True)
    if not isinstance(chunks, (list, tuple)):
        chunks = list(chunks)
    return ''.join(chunks)

''.join(chunks)就是产生这个问题的原因。在pudb控制台中,我设法找到了chunks中产生错误的索引ţ355

In [51]: chunks[355]
Out[51]: '"Datum Erfassung / \xc3\x84nderung"'

文本是"Datum Erfassung / Änderung"。对我来说,这似乎是有效的utf-8代码,this documentation表示对于U+00E4,utf-8十六进制是0xC3 0x84。但如果我这么做了

In [53]: u'Ä'
Out[53]: u'\xc4'

我为什么在这里得到0xC4?你知道吗

在另一个线程中,有人建议使用str转换字符串,以基本上删除编码。所以我试过了

In [54]: ''.join([str(x) for x in chunks])

这次成功了,没有错误。但如果我这么做了:

for ch in chunks:
    if str(ch) != ch:
        print "'%s' differs" % str(ch)

输出仍为空。也不明白为什么''.join(chunk)不起作用,而''.join([str(x) for x in chunks])起作用。你知道吗

我错过了什么?你知道吗

顺便说一句:chardet.detect(chunks[355])输出{'confidence': 0.73, 'encoding': 'Windows-1252', 'language': ''}。真的是这样吗?你知道吗


Tags: 字符串代码inselffor字典asciinot