一:前言
遇到问题:print输入汉字时提示错误信息 UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128)
1:windows环境下
2:脚本已备注:# -*- coding:utf-8 -*-
二:查找解决办法
1:了解python编码格式
在python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错,python没办法处理非ascii编码的。
2:如何查询python的编码格式

3:设置python默认编码格式

可能会报AttributeError: 'module' object has no attribute 'setdefaultencoding'的错误,执行reload(sys),在执行以上命令就可以顺利通过。

此时在执行sys.getdefaultencoding(),就会发现编码已经设置为utf-8了,但是在解释器里修改的编码只能保证档次有效,在重启编译器后,编码又被重置为默认的ascii了
4:一个永久解决的办法
在python的Lib\site-packages文件夹下新建一个sitecustomize.py,内容为:

此时重启python解释器,执行sys.getdefaultencoding(),发现编码已经被设置为utf8的了,多次重启之后,效果相同。
这是因为系统在python启动的时候,自行调用该文件,设置系统的默认编码,而不需要每次都手动的加上解决代码。
三:检验是否解决
输出汉字已经不再报错误了,问题解决了。

参考源文件:http://blog.csdn.net/zuyi532/article/details/8851316
|