0


python string 编解码(encode b64encode)

Since Python 3.0, strings are stored as Unicode, i.e. each character in the string is represented by a code point. So, each string is just a sequence of Unicode code points.

在 Python3 中,有 str, bytes, bytearray。最常用的str type 存储的是 Unicode 字符的coding point,而 bytes type 存储的是 bytes。而且在 Python3 中不会有 bytes 和 str 的隐形转换。

为了有效地存储str字符串,coding point序列被转换为一组字节。该过程称为编码encoding

常见的编码方式有utf-8, ascii, etc.

举个例子:

a = 'helloWord'
  ...: 
a
Out[3]: 'helloWord'
b = a.encode(encoding = 'utf-8')
  ...: 
b
Out[5]: b'helloWord'
print(type(b)) # <class 'bytes'>

可见两种数据格式 str与bytes之间可以通过调用.encode()和.decode()来实现,bytes格式能够更有效的存储,str格式则更容易被人类理解.

现在的b是bytes类型,如果想要传输的话,有个最大问题,即明文传输且过于冗余.

下面引入base64.b64encode

(s, altchars=None

Encode the bytes-like object s using Base64 and return the encoded bytes.

这个函数可以对bytes进行初步加密和压缩,如下

b
Out[5]: b'helloWord'
print(type(b)) # <class 'bytes'>
import base64
bb = base64.b64encode(b)
  ...: 
bb
Out[10]: b'aGVsbG9Xb3Jk'

看见没,压缩之后非常紧凑.如果还想通过http传输,可以把bb再转换回str类型,放在参数里面就可以传输了.

bb
Out[10]: b'aGVsbG9Xb3Jk'

bbb = bb.decode('utf-8')
bbb
Out[13]: 'aGVsbG9Xb3Jk'

现在服务器拿到传输过来的bbb是base64加密压缩之后的数据,我们像转换回原来的明文字符串,进行下一步处理怎么办?下面通过

base64.
b64decode

(s, altchars=None, validate=False)

Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.

完毕!

标签:

本文转载自: https://blog.csdn.net/u010087338/article/details/116421284
版权归原作者 子燕若水 所有, 如有侵权,请联系我们删除。

“python string 编解码(encode b64encode)”的评论:

还没有评论