Python Base64 编码和解码:详解 encodebytes 和 decodebytes 函数

在 Python 中,base64 库提供了 encodebytesdecodebytes 函数,用于进行 Base64 编码和解码操作。

1. Base64 编码

encodebytes 函数将二进制数据编码为 Base64 格式。

import base64

b2 = b'This is a test string.'

# 编码二进制数据
b64_encoded = base64.encodebytes(b2)

print(b64_encoded)

输出结果为:

'VGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg==
'```

**2. Base64 解码**

`decodebytes` 函数将 Base64 编码的字符串解码为二进制数据。

```python
# 解码 Base64 编码的字符串
b2_decoded = base64.decodebytes(b64_encoded)

print(b2_decoded)

输出结果为:

b'This is a test string.'

注意:

  • encodebytes 函数返回的是字节串,需要使用 decode() 方法转换为字符串。
  • decodebytes 函数返回的是字节串,需要使用 decode() 方法转换为字符串。

总结

encodebytesdecodebytes 函数是 Python 中进行 Base64 编码和解码操作的重要工具,可以用于各种场景,例如:

  • 将二进制数据存储在文本文件中。
  • 通过网络传输二进制数据。
  • 加密和解密数据。
Python Base64 编码和解码:详解 encodebytes 和 decodebytes 函数

原文地址: https://www.cveoy.top/t/topic/mSvs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录