结论:中文只能用gbk和utf-8编码,用什么编的码就用什么来解码;gbk每个汉字对应两个字节,utf-8对应三个字节
if __name__ == '__main__':
#结论:中文只能用gbk和utf-8编码,用什么编的码就用什么来解码;gbk每个汉字对应两个字节,utf-8对应三个字节
#一、当文本是中文
u = '中文'
#失败UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)
#str1 = u.encode("ISO-8859-1")
str1 = u.encode("gbk")
print(str1)
#1、成功b'\xd6\xd0\xce\xc4'
str2 = str1.decode("gbk")
#2、失败UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
#str2 = str1.decode("utf-8")
#3、乱码ÖÐÎÄ
#str2 = str1.decode("ISO-8859-1")
print(str2)
str1 = u.encode("utf-8")
print(str1)
#1、成功b'\xe4\xb8\xad\xe6\x96\x87'
str2 = str1.decode("utf-8")
#2、失败UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 2: illegal multibyte sequence
#str2 = str1.decode("gbk")
#3、乱码ä¸æ–‡
#str2 = str1.decode("ISO-8859-1")
print(str2)
#二、当文本是字母
u = 'a'
#成功b'a'
str1 = u.encode("ISO-8859-1")
print(str1)
#三种均可解码
str2 = str1.decode("ISO-8859-1")
print(str2)
str3 = str1.decode("gbk")
print(str2)
str4 = str1.decode("utf-8")
print(str2)