【python】浅谈encode和decode

对于encode和decode,笔者也是根据自己的理解,有不对的地方还请多多指点。

当前主流的编码格式:

  • ASCII码

         其最多只能用 8 位来表示(一个字节),即:2**8 = 256-1,所以,ASCII码最多只能表示 255 个符号。

 

  • GB2312

         GB2312就是在ASCII基础上的简体汉字扩展,GB2312(1980年)一共收录了7445个字符

  • GBK

         GBK是对GB2312的进一步扩展(K是汉语拼音kuo zhan(扩展)中“扩”字的声母), 收录了21886个汉字和符号,完全兼容GB2312。

  • GB18030

          GB18030收录了70244个汉字和字符,更加全面,与 GB 2312-1980 和 GBK 兼容

  • Unicode(可以代表所有字符和符号的编码)

             Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,规定虽有的字符和符号最少由 16 位来表示(2个字节),即:2 **16 = 65536, 注:此处说的的是                 最少2个字节,可能更多。

            UTF-8,是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存... 所以,python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill)

编码的理解(Encode):

字符串通过编码转换为字节,str--->(encode)--->bytes,编码时需要把编码格式传给encode方法。

解码的理解(Encode):

字节通过解码转换为字符串,bytes--->(decode)--->str,解码时需要把编码格式传给decode方法。

 

word="你好"
print (word)
#>>> 你好
print(type(word))
#>>><class 'str'>

word_utf8=word.encode("utf-8")
print (word_utf8)
#>>>b'xe4xbdxa0xe5xa5xbd'
print(type(word_utf8))
#>>><class 'bytes'>

word_gbk=word.encode("gbk")
print (word_gbk)
#>>>b'xc4xe3xbaxc3'
print(type(word_gbk))
#>>><class 'bytes'>

word_utf8_str=word_utf8.decode("utf-8")
print (word_utf8_str)
#>>>你好
print(type(word_utf8_str))
#>>><class 'str'>

word_gbk_str=word_gbk.decode("gbk")
print (word_gbk_str)
#>>>你好
print(type(word_gbk_str))
#>>><class 'str'>

不同编码的转换:

>>>python2:

python2,默认为ascii

      

##比如utf-8转换为gbk
word="你好"
word.decode("utf-8").encode("gbk")
##比如gbk转换为utf-8
word="你好"
word.decode("gbk").encode("utf-8")

>>>python3:

python3,默认为unicode
#-*- coding:utf-8 -*-   ###文件编码

"""python3 默认字符集编码是Unicode,文件的编码不会影响字符集编码"""

import  sys
print(sys.getdefaultencoding())
#>>>utf-8       ###打印文件编码
word="你好"    ##字符编码默认还是Unicode
print(word.encode("utf-8"))   ##Unicode 转换为utf-8,由于python3的encode()方法也会把str转换为bytes
#>>>b'xe4xbdxa0xe5xa5xbd'
print(word.encode("gbk"))   ##Unicode 转换为gbk,由于python3的encode()方法也会把str转换为bytes
#>>>b'xc4xe3xbaxc3'
print(word.encode("utf-8").decode("utf-8"))##先由Unicode 转换为utf-8,再由utf-8转换为Unicode,同理先由str转换为bytes,再由bytes转换为str
#>>>你好
print(word.encode("utf-8").decode("utf-8").encode('gbk'))##先由Unicode 转换为utf-8,再由utf-8转换为Unicode,最后再Unicode 转换为gbk,
                                                        # 同理先由str转换为bytes,再由bytes转换为str,最后str转换为bytes
#>>>b'xc4xe3xbaxc3'

  

 

原文地址:https://www.cnblogs.com/paulwinflo/p/3853064.html