python encode decode
阅读原文时间:2023年07月08日阅读:1

Python encode()
encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
写法:
str.encode(encoding='UTF-8',errors='strict')
参数
encoding -- 要使用的编码,如"UTF-8"。
errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
返回值:该方法返回编码后的字符串。

Python decode()
decode() 方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。
写法:
str.decode(encoding='UTF-8',errors='strict')
参数
encoding -- 要使用的编码,如"UTF-8"。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值:该方法返回解码后的字符串。

实例
以下实例展示了decode()方法的实例:

实例(Python 3.7)

>>> aa="abcdfsdf"
>>> ab=aa.encode(encoding='utf-8')
>>> print(ab)
b'abcdfsdf'
>>> print(ab.decode(encoding='utf-8'))
abcdfsdf
>>>

import base64
str = "this is string examlkidiple….wow!!!";
str = base64.b64encode(bytes(str,'utf-8'))
print ("Encoded String: " , str)
print ("Decoded String: " ,base64.b64decode(str))
s=b'More\xe6\x9b\xb4\xe5\xa4\x9a\xe8\xaf\xb7\xe5\x85\xb3\xe6\xb3\xa8\xe6\x88\x91'
print(s.decode('utf-8'))
#乱码来自s.encode('gbk').decode('ISO-8859-1')
s='More¸ü¶àÇë¹Ø×¢ÎÒ'.encode('ISO-8859-1').decode('gbk')
print(s)
结果:

Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbWxraWRpcGxlLi4uLndvdyEhIQ=='
Decoded String: b'this is string examlkidiple….wow!!!'
More更多请关注我
More更多请关注我
>>>