1.在python源码里出现了中文
在源码开头加上字符编码的声明,用一个特殊的注释行来定义字符集。
比如# -*- coding: utf-8 -*
或 #encode=utf-8
2.操作中文字符
python中有两种默认的字符串:str和unicode,<type 'str'>
将字符串看作是字节序列, <type 'encode'>
将字符串看作是字符的序列。python内部使用的unicode编码,decode是将普通字符串按照参数中的编码格式进行解析,生成unicode对象;encode是将unicode对象转换成参数中编码格式的普通字符串。
str—>unicode :decode(‘utf-8’)
unicode—>str :encode(‘utf-8’)
3.从文件中读取的内容包含中文
python默认采用的是ascii编码,用sys.setdefaultencoding('utf-8')
可以改变默认编码。但在加载sys模块时会自动删除setdefaultencoding(),直接用该方法会设置编码参数会报错,所以要重新加载sys模块
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
-
json.dumps()把python原始类型编码成json类型;json.loads()把json类型解码成python原始类型
当str包含中文,用
json.dumps()
方法编码报错时
json.loads()
和
json.dumps()
import json
jsonStr = json.loads(str)
resultStr = json.dumps(jsonStr, ensure_ascii=False)
#resultStr = json.dumps(jsonStr, ensure_ascii=False, encoding='utf-8').encode('utf-8')