Python2的编解码

python2中程序数据类型默认为ASCII,所以需要先将数据解码(decode)成为Unicode类型,然后再编码(encode)成为想要转换的数据类型(gbk,utf-8,gb18030,gb2312),然后再解码成为对应的数据类型显示在屏幕上;

Python3的编解码

python3中程序默认数据类型为Unicode,所以直接将数据编码(encode)成为想要转换的数据类型(gbk,utf-8,gb18030,gb2312),然后解码成为对应的数据类型显示在屏幕上。

base64

Base64编码是一种“防君子不防小人”的编码方式。广泛应用于MIME协议,作为电子邮件的传输编码,生成的编码可逆,后一两位可能有“=”,生成的编码都是ascii字符。

因此对于python2来说,编解码相对要容易一些。python3因为要从Unicode转换一下,相对麻烦一些。一切见下例:

  • Python2
 1 def b64encode(s, altchars=None):
 2     """Encode a string using Base64.
 3 
 4     s is the string to encode.  Optional altchars must be a string of at least
 5     length 2 (additional characters are ignored) which specifies an
 6     alternative alphabet for the '+' and '/' characters.  This allows an
 7     application to e.g. generate url or filesystem safe Base64 strings.
 8 
 9     The encoded string is returned.
10     """
11     # Strip off the trailing newline
12     encoded = binascii.b2a_base64(s)[:-1]
13     if altchars is not None:
14         return encoded.translate(string.maketrans(b'+/', altchars[:2]))
15     return encoded
 1 def b64decode(s, altchars=None):
 2     """Decode a Base64 encoded string.
 3 
 4     s is the string to decode.  Optional altchars must be a string of at least
 5     length 2 (additional characters are ignored) which specifies the
 6     alternative alphabet used instead of the '+' and '/' characters.
 7 
 8     The decoded string is returned.  A TypeError is raised if s is
 9     incorrectly padded.  Characters that are neither in the normal base-64
10     alphabet nor the alternative alphabet are discarded prior to the padding
11     check.
12     """
13     if altchars is not None:
14         s = s.translate(string.maketrans(altchars[:2], '+/'))
15     try:
16         return binascii.a2b_base64(s)
17     except binascii.Error, msg:
18         # Transform this exception for consistency
19         raise TypeError(msg)
b64decode源码

相关文章:

  • 2021-12-22
  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2021-12-02
  • 2021-11-25
猜你喜欢
  • 2022-12-23
  • 2021-12-25
  • 2021-12-18
  • 2021-06-12
  • 2021-11-20
  • 2022-01-15
  • 2021-12-18
相关资源
相似解决方案