python中文处理相信迷惑过不少同学。下面说说python2/3的encode和decode函数。
python2中,使用decode()和encode()来进行解码和编码,以unicode类型作为中间类型。即 decode encodestr ---------> unicode --------->str
示例(注意encode和decode的编码必须保持一致):
u = u'中文' #unicode对象ugb2312_str = u.encode('gb2312') #gb2312编码字符串gbk_str = u.encode('gbk') #gbk编码字符串utf8_str = u.encode('utf-8') #utf-8编码字符串gb2312_u = gb2312_str.decode('gb2312') #gb2312编码的unicodeutf8_u = gb2312_str.decode('utf-8') #utf-8编码的unicode,此处因为编解码方法不一致将导致无法还原原unicode类型
python2编解码处理给人的感觉是较复杂。于是在python3中取消了unicode类型,代替以unicode编码的字符串类型str。str和bytes关系如下: encode decodestr ---------> bytes --------->str
转载于:https://www.cnblogs.com/tudas/p/python-encode-decode.html