Python中文编码问题的解决办法

Python使用时,经常出现各种编码的问题。这里汇总一下常用的解决办法。

万能开头代码

#coding=utf-8
import sys
reload(sys)   #必须要reload
sys.setdefaultencoding('utf-8')

分析

方法一 原文件编码声明

#放在原文件第一行
#coding=utf-8

方法二 默认编码修改

查看python的默认编码

import sys
print sys.getdefaultencoding()

更改python默认编码

import sys
reload(sys)   #必须要reload
sys.setdefaultencoding('utf-8')

疑难问题

UnicodeDecodeError解决办法

通常情况使用前面的两种方法,基本不会有什么问题。但是最近还是碰到编码的问题。

在往一个函数传递字符串时出现的错误:
exceptions.UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xce in position 0: invalid continuation byte
解决办法:

对字符串进行unicode化,忽略错误,代码如下:

unicode( rst , errors='ignore')
© 版权声明
THE END
广告
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情

    暂无评论内容