python中decode和encode的区别和联系

来源:互联网 发布:球球大作战圣衣软件 编辑:程序博客网 时间:2024/06/07 05:42

编码问题:decode和encode的区别和联系
python中,我们使用decode()和encode()来进行解码和编码。使用unicode类型作为编码的基础类型。即

str —-(decode)—–> unicode —–(encode)—->str

  • 字符串在python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

  • decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串转换成unicode编码。

  • encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串转换成gb2312编码。

例子:

>>> str = '你好世界'>>> print str你好世界>>> type(str)<type 'str'>#字符串转为Unicode>>> str =u'你好,世界'>>> type(str)<type 'unicode'>>>> len(str)5#将Unicode编码转为utf-8编码>>> str.encode('utf-8')'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'#utf-8编码,一个汉字占用两个字节;GBK编码一个汉字占用一个字节>>> len(str.encode('utf-8'))15#将utf-8编码的字符串解码为Unicode>>> str.decode('utf-8')u'\u4f60\u597d\uff0c\u4e16\u754c'