本文实例讲述了Python设置默认编码为utf8的方法。分享给大家供大家参考,具体如下:
这是Python的编码问题,设置python的默认编码为utf8
python安装目录:/etc/python2.x/sitecustomize.py
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
try:
import apport_python_hook
except ImportError:
pass
else:
apport_python_hook.install()
[b]如果在windows下:[/b]
可以在Python安装目录下的Lib/site-packages目录中,新建一个sitecustomize.py文件(也可以建在其它地方,然后手工导入,建在这里,每次启动Python的时候设置将自动生效),内容如下:
import sys
sys.setdefaultencoding('utf-8') #set default encoding to utf-8
然后可以查看到改变已经生效
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
此时运行程序,如果仍然报告之前的错误,只需要显示地设定输出的编码
就可以看到正确显示。
更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/645.htm]Python图片操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》
希望本文所述对大家Python程序设计有所帮助。