解决UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 108: ordinal not in range(128
今天作网页到了测试和数据库交互的地方,其中HTML和数据库都是设置成utf-8格式编码,插入到数据库中是正确的,可是当读取出来的时候就会出错,缘由就是python的str默认是ascii编码,和unicode编码冲突,就会报这个标题错误。那么该怎样解决呢?html
经过搜集网上的资料,本身屡次尝试,问题算是解决了,在代码中加上以下几句便可。python
import sys reload(sys) sys.setdefaultencoding('utf8')
参考资料:http://groups.google.com/group/python-cn/browse_thread/thread/f48ef745452740f6?pli=1数据库
点击打开连接测试
混淆了 python2 里边的 str 和 unicode 数据类型。编码
0.spa
你须要的是让编码用实际编码而不是 asciicode
1.htm
对须要 str->unicode 的代码,能够在前边写上blog
import sys
reload(sys)
sys.setdefaultencoding(‘utf8′)
把 str 编码由 ascii 改成 utf8 (或 gb18030)
2.
python3 区分了 unicode str 和 byte arrary,而且默认编码再也不是 ascii