UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 537: ordinal not in range(128), referer: ...
I always get this error when I try to output my whole website with characters "č". I am using mako templating. What to do?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 537: ordinal not in range(128), referer: ...
I always get this error when I try to output my whole website with characters "č". I am using mako templating. What to do?
发生错误是因为某处代码将您的 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 locale
, man setlocale
.
对于 Linux,还需要安装语言包,例如sudo apt-get install language-pack-en
.
您可以使用以下代码替换特殊字符 č: č
"your string".replace('č','č')
如果您在网站上工作,您可以为所有特殊字符创建一个 sanytize 函数。