UnicodeDecodeError:“ascii”编解码器无法解码位置23中的字节0xc3:序号不在范围(128)内

2024-06-11 08:02:19 发布

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

当我尝试连接这个时,当字段包含'nin'或''。如果包含“nin”或“’”的字段是最后一个,则不会出错。

#...

nombre = fabrica
nombre = nombre.encode("utf-8") + '-' + sector.encode("utf-8")
nombre = nombre.encode("utf-8") + '-' + unidad.encode("utf-8")

#...

return nombre 

知道吗?非常感谢!


Tags: returnutfencodesectorninnombreunidadfabrica
3条回答

当您得到一个UnicodeEncodeError时,这意味着在代码中的某个地方,您可以直接将字节字符串转换为unicode字符串。默认情况下,在Python 2中它使用ascii编码,在Python3中使用utf8编码(这两种编码都可能失败,因为不是每个字节在两种编码中都有效)

为了避免这种情况,必须使用显式解码。

如果输入文件中可能有两种不同的编码,其中一种接受任何字节(如UTF8和Latin1),则可以尝试先将字符串转换为first,如果发生UnicodeDecodeError,则使用第二种编码。

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

如果不知道原始编码并且不关心非ascii字符,可以将decode方法的可选errors参数设置为replace。任何有问题的字节都将被替换(从标准库文档中):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

当我在python3中执行时出现了这个错误,我只需在python2中执行就可以得到相同的程序

您正在编码到UTF-8,然后re-编码到UTF-8。Python只有先将解码为Unicode时才能执行此操作,但它必须使用默认的ASCII编解码器:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

不要继续编码;将编码留给UTF-8直到最后一个可能的时刻。改为连接Unicode值。

您可以在这里使用str.join()(或者,更确切地说,使用unicode.join())将这三个值与中间的破折号连接起来:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

但即使在这里编码也可能为时过早。

经验法则:解码接收到值的时刻(如果不是API已经提供的Unicode值),仅在必须时编码(如果目标API不直接处理Unicode值)。

相关问题 更多 >