gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:36:44 29 4
gpt4 key购买 nike

当我尝试连接它时,当字段包含“ñ”或“´”时,我会收到 UnicodeDecodeError。如果包含“ñ”或“´”的字段是最后一个,我不会出错。

#...

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

#...

return nombre

有什么想法吗?非常感谢!

最佳答案

您正在编码为 UTF-8,然后 重新-编码为 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 值)。

关于python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475393/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com