decode
解碼
s = '呵呵'
sg = sg.encode('gbk') # 將呵呵編碼成gbk格式
print(sg)
s1 = sg.decode('gbk') # 將呵呵使用gbk解碼成unicode格式(使用什么方式編碼就需要對應(yīng)的方式解碼)
print(s1)
# 這里如果sg使用utf-8解碼會拋出UnicodeDecodeError
s3 = sg.decode('utf-8')
output:
b'\xe5\x93\x88\xe5\x93\x88'
呵呵
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
encode
編碼
s = '哈哈'
su = s.encode('utf-8')
print(su)
output:
b'\xe5\x93\x88\xe5\x93\x88' # utf-8格式的‘哈哈’
encoding
指定編碼格式
unicode
unicode編碼字符串可以表示更多的字符集,Python3中默認的字符串是unicode,unicode字符串可以編碼成utf-8,gbk,gb2312等等,同樣的utf-8.gbk,gb2312等字符串也可以解碼成unicode字符串,unicode字符串可以當做一個中間轉(zhuǎn)換的編碼