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.
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