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

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

问题描述

当我尝试连接这个,当字段包含'ñ'或'''时,我得到UnicodeDecodeError。如果包含'ñ'或'''的字段是最后一个,我没有收到错误。

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 

任何想法?非常感谢!

推荐答案

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

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')
'\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 到最后的可能时刻

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

您可以使用 str.join()(或者,而是 unicode.join())在这里连接三个值之间的破折号:

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.

经验法则:解码收到该值的时间(如果不是Unicode值)通过API已经),只有当你必须(如果目标API不直接处理Unicode值)时才编码。

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天全站免登陆