s = "hello world"
# 1. 字符串---编码 字节数据 = 字符串数据.encode(方案) ---> 字节
b1 = s.encode()
b2 = s.encode(encoding="utf-8") # 默认参数就是utf-8 一个参数对应 3 个字节
b3 = s.encode(encoding="gbk") # 一个汉字对应2个字节
# print(type(s), type(b1)) # 输出<class 'str'> <class 'bytes'>
# print(b1, b3) #输出 b'hello \xe5\xb0\x8f\xe5\xa7\x90\xe5\xa7\x90' b'hello \xd0\xa1\xbd\xe3\xbd\xe3'
# 2. 字节----解码 字符串数据=字节数据.decode(方案)----> 字符串
s2 = b2.decode()
s3 = b2.decode(encoding="utf-8") # 默认参数就是 utf-8
# print(type(s2), s2) # 输出 <class 'str'> hello 小姐姐
# print(type(s3), s3) # 输出 <class 'str'> hello 小姐姐
# 3. #s33 = b3.decode(encoding="utf-8") 解码报错
s33 = b3.decode(encoding="GBK") # 解码采用方案必须和该数据编码的方案一致
print(type(s33), s33) # 输出 <class 'str'> hello 小姐姐
python 字节和字符串的转换 解码和编码
猜你喜欢
转载自blog.csdn.net/LanlanDeming/article/details/103672293
今日推荐
周排行