python中的编码与解码

python中文件编码默认为utf-8,字符编码默认为unicode,

一个例子:

s = '我家小馆'
print(s)
unicode_to_utf8 = s.encode('utf-8')
unicode_to_gbk = s.encode('gbk')
print('utf8:',unicode_to_utf8)
print('gbk:',unicode_to_gbk)

gbk_to_unicode = unicode_to_gbk.decode('gbk')
unicode_to_utf8 = gbk_to_unicode.encode('utf-8')

print(gbk_to_unicode)
print(unicode_to_utf8)

结果为:
我家小馆
utf8: b'xe6x88x91xe5xaexb6xe5xb0x8fxe9xa6x86'
gbk: b'xcexd2xbcxd2xd0xa1xb9xdd'
我家小馆
b'xe6x88x91xe5xaexb6xe5xb0x8fxe9xa6x86'
可以看出unicode编码的字符可以直接显示汉字,
而utf-8的汉字为三个字节一个字符,gbk的汉字为两个字符一个汉字。
从unicode-->utf8为编码encode
从utf8-->unicode为解码decode

原文地址:https://www.cnblogs.com/MY0213/p/7767370.html