繁体   English   中英

UnicodeDecodeError:'ascii'编解码器无法解码字节0xc5

[英]UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 537: ordinal not in range(128), referer: ...

当我尝试使用字符“č”输出整个网站时,我总是收到此错误。 我正在使用mako模板。 该怎么办?

发生错误是因为某处代码将您的unicode模板字符串强制转换为python 2 str ; 您需要自己将渲染的模板编码为UTF-8字节串:

if isinstance(rendered, unicode):
    rendered = rendered.encode('UTF-8')

# rendered is now guaranteed to be of type str

问题是您的代码因为超过8位而无法解码某些字符,因此请尝试使用此代码:

converted = unicode("your_string", encoding="utf-8", errors="ignore")

祝好运

确保使用正确的区域设置运行脚本,例如

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

文件: man localeman setlocale

对于Linux,还要安装语言包,例如sudo apt-get install language-pack-en

您可以使用以下代码替换您的特殊字符č:č

"your string".replace('č','č')

如果您正在网站上工作,您可以为所有特殊字符创建一个sanytize功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM