UnicodeDecodeError:“ascii"编解码器无法解码位置 23 中的字节 0xc3:序号不在范围内(128) [英] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

查看:28
本文介绍了UnicodeDecodeError:“ascii"编解码器无法解码位置 23 中的字节 0xc3:序号不在范围内(128)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#...nombre =fabricanombre = nombre.encode("utf-8") + '-' + 扇区.encode("utf-8")nombre = nombre.encode("utf-8") + '-' + unidad.encode("utf-8")#...返回名称

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

解决方案

您要编码为 UTF-8,然后重新-编码为 UTF-8.Python 只能在再次解码到 Unicode 时才能做到这一点,但它必须使用默认的 ASCII 编解码器:

<预><代码>>>>联合国'你'xf1'>>>u'ñ'.encode('utf8')'xc3xb1'>>>u'ñ'.encode('utf8').encode('utf8')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xc3:序号不在范围内 (128)

不要继续编码;将编码保留为 UTF-8 到最后一刻.改为连接 Unicode 值.

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

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

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

经验法则:在收到值的那一刻解码(如果不是 API 提供的 Unicode 值),仅在需要时才编码(如果目标 API 不直接处理 Unicode 值).

when I try to concatenate this, I get the UnicodeDecodeError when the field contains 'ñ' or '´'. If the field that contains the 'ñ' or '´' is the last I get no error.

#...

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

#...

return nombre 

any idea? Many thanks!

解决方案

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'xf1'
>>> u'ñ'.encode('utf8')
'xc3xb1'
>>> 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)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

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

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

这篇关于UnicodeDecodeError:“ascii"编解码器无法解码位置 23 中的字节 0xc3:序号不在范围内(128)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆