前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中encode和decode的区别_python rindex

python中encode和decode的区别_python rindex

作者头像
全栈程序员站长
发布2022-11-08 14:43:35
3710
发布2022-11-08 14:43:35
举报
文章被收录于专栏:全栈程序员必看

1.基本语法

1.encode()和decode()都是字符串的函数

代码语言:javascript
复制
      decode解码             encode编码
str ---------> str(Unicode,byte类型) ---------> str

2.decode()与encode()方法可以接受参数,其声明分别为:

其中的encoding是指在解码编码过程中使用的编码(此处指“编码方案”是名词),errors是指错误的处理方案。

代码语言:javascript
复制
bytes.decode(encoding="utf-8", errors="strict")
str.encode(encoding="utf-8", errors="strict")

3.查看官网关于encode与decode方法的使用说明如下:

1.str.encode(encoding=”utf-8″, errors=”strict”)

Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace','backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

2.bytes.decode(encoding=”utf-8″, errors=”strict”)

Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered viacodecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

2.使用演示与注意事项

代码语言:javascript
复制
a = '编码测试'

#使用不同的编码格式给a进行编码
b = a.encode('utf-8')
c = a.encode('gb2312') #发现gb2312和gbk结果一样
d = a.encode('gbk')
print(type(b),b)
print(type(c),c)
print(type(d),d)
'''
<class 'bytes'> b'\xe7\xbc\x96\xe7\xa0\x81\xe6\xb5\x8b\xe8\xaf\x95'
<class 'bytes'> b'\xb1\xe0\xc2\xeb\xb2\xe2\xca\xd4'
<class 'bytes'> b'\xb1\xe0\xc2\xeb\xb2\xe2\xca\xd4'
'''
#使用不同的解码方式解码
b1 = b.decode('utf-8')
c1 = c.decode('gb2312')
d1 = d.decode("gbk")
b11 = b.decode('gbk')  #b本来是用utf-8编码,现在用gbk进行解码,出现乱码的情况
print(type(b1),b1)
print(type(c1),c1)
print(type(d1),d1)
print(type(b11),b11)  #b本来是用utf-8编码,现在用gbk进行解码,出现乱码的情况
'''
<class 'str'> 编码测试
<class 'str'> 编码测试
<class 'str'> 编码测试
<class 'str'> 缂栫爜娴嬭瘯
'''
  • 字符串通过编码成为字节码,字节码通过解码成为字符串。
  • 字符串或者字节只能同时拥有一个方法 ,要么解码要么编码

统一声明:关于原创博客内容,可能会有部分内容参考自互联网,如有原创链接会声明引用;如找不到原创链接,在此声明如有侵权请联系删除哈。关于转载博客,如有原创链接会声明;如找不到原创链接,在此声明如有侵权请联系删除哈。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/185267.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年10月6日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.基本语法
  • 2.使用演示与注意事项
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档