python中encode和decode使用讲解与演示

python中encode和decode使用讲解与演示1 基本语法 1 encode 和 decode 都是字符串的函数 decode 解码 encode 编码 str gt str Unicode byte 类型 gt str 2 decode 与 encode 方法可以接受参数 其声明分别为

大家好,我是讯享网,很高兴认识大家。

 1.基本语法

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

   decode解码             encode编码 str ---------> str(Unicode,byte类型) ---------> str

讯享网

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

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

讯享网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.使用演示与注意事项

 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'> 缂栫爜娴嬭瘯 '''
  • 字符串通过编码成为字节码,字节码通过解码成为字符串。 
  • 字符串或者字节只能同时拥有一个方法 ,要么解码要么编码

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

小讯
上一篇 2025-02-22 19:48
下一篇 2025-01-06 14:33

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/128026.html