派森学长带你学python—字符串(3)

一.字符串的编码与解码

计算机之间传输信息是通过二进制bytes类型数据进行传送的

即将输入数据转换成bytes类型的过程叫编码,将bytes类型转换成原输入数据类型的过程叫做解码

字符串的编码:encode()

语法格式:str.encode(encoding='utf-8',errors='strict/ignore/replace')
#errors表示出错的解决方法

字符串的解码:decode()

语法格式:bytes.decode(encoding='utf8',errors='strict/ignore/replace')
#使用utf-8编码,就要使用utf-8解码;使用GBK编码,就要使用GBK解码

1.1 编码

#编码
a='健康快乐幸福'
score=a.encode(errors='replace')
print(score)#在utf-8编码中,一个汉字占8个字节,b'\xe5\x81\xa5\xe5\xba\xb7\xe5\xbf\xab\xe4\xb9\x90\xe5\xb9\xb8\xe7\xa6\x8f'
score=a.encode(encoding='GBK',errors='ignore')
print(score)#在GBK编码中,一个汉字占2个字节,b'\xbd\xa1\xbf\xb5\xbf\xec\xc0\xd6\xd0\xd2\xb8\xa3'
b='北京✋'
score=b.encode(encoding='GBK',errors='ignore')
print(score)#b'\xb1\xb1\xbe\xa9'
'''score=b.encode(encoding='GBK',errors='strict')
print(score)#报错
'''

1.2 解码

b='健康快乐幸福'
score=b.encode(encoding='gbk',errors='ignore')
print(score)#str-bytes b'\xbd\xa1\xbf\xb5\xbf\xec\xc0\xd6\xd0\xd2\xb8\xa3'
#解码
print(bytes.decode(score,encoding='gbk',errors='ignore'))#bytes-str 健康快乐幸福

1.3 练习

c='我爱中国'
cc=c.encode('utf-8','replace')
print(cc)#b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'
print(bytes.decode(cc,'utf-8','replace'))#我爱中国

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

派森学长

让我们一起学习python

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值