Python-'ASCII'编解码器无法解码字节 [英] Python - 'ascii' codec can't decode byte

查看:120
本文介绍了Python-'ASCII'编解码器无法解码字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.6和Jinja2创建HTML报告.我为模板提供了很多结果,并且模板遍历它们并创建HTML表

I'm using Python 2.6 and Jinja2 to create HTML reports. I provide the template with many results and the template loops through them and creates HTML tables

在调用template.render时,我突然开始收到此错误.

When calling template.render, I've suddenly started getting this error.

<td>{{result.result_str}}</td>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)

奇怪的是,即使我为每个结果将result.result_str设置为简单的ascii字符串(如"abc"),我仍然会看到此错误.我是Jinja2和Python的新手,对于我如何调查问题以找到根本原因,我将不胜感激.

The strange thing is, even if I set result.result_str to a simple ascii string like "abc" for every result, I am still seeing this error. I'm new to Jinja2 and Python and would appreciate any ideas on how I can go about investigating the problem to get to the root cause.

推荐答案

如果您遇到诸如"ABC"之类的字符串错误,则可能是非ASCII字符在其他地方.也许在模板源中?

If you get an error with a string like "ABC", maybe the non-ASCII character is somewhere else. In the template source perhaps?

在任何情况下,都应在整个应用程序中使用Unicode字符串,以避免此类问题.如果您的数据源为您提供了字节字符串,并且该字符串以UTF-8编码,则您将获得byte_string.decode('utf-8')的unicode字符串.如果您的源文件是文件,请使用编解码器模块中的StreamReader类.

In any case, use Unicode strings throughout your application to avoid this kind of problems. If your data source provides you with byte strings, you get unicode strings with byte_string.decode('utf-8'), if the string is encoded in UTF-8. If your source is a file, use the StreamReader class in the codecs module.

如果不确定Unicode字符串和常规字符串之间的区别,请阅读以下内容: http: //www.joelonsoftware.com/articles/Unicode.html

If you're unsure about the difference between Unicode strings and regular strings, read this: http://www.joelonsoftware.com/articles/Unicode.html

这篇关于Python-'ASCII'编解码器无法解码字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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