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

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

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

发布了248 篇原创文章 · 获赞 1600 · 访问量 267万+

猜你喜欢

转载自blog.csdn.net/qq_26442553/article/details/94440502
今日推荐