
编码方式的历史大致为ASCII ->gb2312->unicode->utf-8,期间具体详细信息感兴趣的可以去做一些查询,正因为存在这样的过渡,因此对同一模块的不同使用,需要我们去进行有选择性的挑选使用,因此,这就衍生出了我们今天的主题,怎么去对比使用这些存在的编码方式。
来个编码解码的小例子先,记住中文可以进行GBK和utf-8编码,在GBk一个中文字符对应两个字节,在utf-8一个中文字符对应三个字节,中文不能进行ASCII编码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> '爬森' .encode( 'GBK' )
b '\xc1\xf5\xc8\xf3\xc9\xad'
>>> '爬森' .encode( 'ascii' )
Traceback (most recent call last):
File "<stdin>" , line 1, in <module>
UnicodeEncodeError: 'ascii' codec can 't encode characters in position 0-2: ordinal not in range(128)
>>> ' Runsen '.encode(' ascii ')
b' Runsen '
>>> "爬森".encode(' utf-8 ')
b' \xe5\x88\x98\xe6\xb6\xa6\xe6\xa3\xae '
>>> ' 爬森 '.encode(' GBK ').decode(' GBK ')
' 爬森 '
>>> ' 爬森 '.encode(' GBK ').decode(' utf-8 ')
UnicodeDecodeError: ' utf-8 ' codec can' t decode byte 0xc1 in position 0: invalid start byte
|
如果编码解码格式不一致可能会出现乱码,encode表示编码,decode表示解码,这样大家可以对选择上有明确想法了吧,如果还想知道更多相关内容,进入python学习网即可。