python中文处理之encode/decode函数

时间:2022-03-10 17:43:24

python中文处理相信迷惑过不少同学。下面说说python2/3的encode和decode函数。

python2中,使用decode()和encode()来进行解码和编码,以unicode类型作为中间类型。即
    decode             encode
str ---------> unicode --------->str

示例(注意encode和decode的编码必须保持一致):

u = u'中文'                       #unicode对象u
gb2312_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编码的unicode
utf8_u = gb2312_str.decode('utf-8')        #utf-8编码的unicode,此处因为编解码方法不一致将导致无法还原原unicode类型

python2编解码处理给人的感觉是较复杂。于是在python3中取消了unicode类型,代替以unicode编码的字符串类型str。str和bytes关系如下:
    encode              decode
str ---------> bytes --------->str