python3默认编码为unicode,由str类型进行表示。二进制数据使用byte类型表示。
字符串通过编码转换成字节码,字节码通过解码成为字符串
encode:str --> bytes
decode:bytes --> str
str = "我是Python3" str_utf8 = str.encode('utf-8') str_gbk = str.encode('GBK') print(str) print("UTF-8 编码:", str_utf8) print("GBK 编码:",str_gbk) print("UTF-8 解码:", str_utf8.decode('utf-8')) print("GBK解码:",str_gbk.decode('GBK'))
输出结果如下
我是Python3 UTF-8 编码: b'xe6x88x91xe6x98xafPython3' GBK 编码: b'xcexd2xcaxc7Python3' UTF-8 解码: 我是Python3 GBK解码: 我是Python3