python3编解码 encode decode

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'\xe6\x88\x91\xe6\x98\xafPython3'
GBK 编码: b'\xce\xd2\xca\xc7Python3'
UTF-8 解码: 我是Python3
GBK解码: 我是Python3

  

 

 

猜你喜欢

转载自www.cnblogs.com/kongrui/p/13194947.html