一、 str与bytes 互转
a = 'abcd' b = b'abcde' # str to bytes print(bytes(a, encoding="utf-8")) # 必须制定编码格式 # bytes to str print(bytes.decode(b))
运行结果:
b'abcd'
abcde
二、base64详解
base64是把二进制字符串转换成base64编码的字符串,base64的长度永远是4的倍数。
>>> dir(base64)
['MAXBINSIZE', 'MAXLINESIZE', '_85encode', '_A85END', '_A85START', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_a85chars', '_a85chars2', '_b32alphabet', '_b32rev', '_b32tab2', '_b85alphabet', '_b85chars', '_b85chars2', '_b85dec', '_bytes_from_decode_data', '_input_type_check', '_urlsafe_decode_translation', '_urlsafe_encode_translation', 'a85decode', 'a85encode', 'b16decode', 'b16encode', 'b32decode', 'b32encode', 'b64decode', 'b64encode', 'b85decode', 'b85encode', 'binascii', 'bytes_types', 'decode', 'decodebytes', 'decodestring', 'encode', 'encodebytes', 'encodestring', 'main', 're', 'standard_b64decode', 'standard_b64encode', 'struct', 'test', 'urlsafe_b64decode', 'urlsafe_b64encode']
主要用到的方法:'b64decode', 'b64encode','urlsafe_b64decode', 'urlsafe_b64encode'
1、b64encode
Help on function b64encode in module base64:
b64encode(s, altchars=None)
Encode the bytes-like object s using Base64 and return a bytes object.
Optional altchars should be a byte string of length 2 which specifies an
alternative alphabet for the '+' and '/' characters. This allows an
application to e.g. generate url or filesystem safe Base64 strings.
把bytes字符串编码成Base64,返回的是bytes。>>> base64.b64encode(s)
b'YWJjZA=='
2、b64decode
Help on function b64decode in module base64:
b64decode(s, altchars=None, validate=False)
Decode the Base64 encoded bytes-like object or ASCII string s.
把Base64编码的字符串解码成bytes或者str>>> base64.b64decode(b'YWJjZA==')
b'abcd'
3、'urlsafe_b64decode', 'urlsafe_b64encode'
标准的Base64可能出现字符+和/,在URL中就不能直接作为参数,urlsafe_b64encode和urlsafe_b64decode就是把字符+和/分别变成-和_。用法和b64encode一致。
4、模拟处理cookies中去除“=”的base64编码字符串
import base64 import re # 处理去除等号的base64 def handle_no_equal_base(ch): if len(ch) % 4 == 1: ch = ch + b"=" if len(ch) % 4 == 2: ch = ch + b"==" return ch s = base64.b64encode(b"abcd") s = bytes("".join(re.split("=", bytes.decode(s))), encoding='utf-8') print(base64.b64decode(handle_no_equal_base(s)))