【Python】基于base64对文本进行编码
将字符串转换为Base64编码
import base64
"""
首先将原始字符串转换为字节,然后使用base64.b64encode()方法将字节转换为Base64编码
"""
# 原始字符串
original_string = "Hello, World!"
# 将字符串转换为字节
byte_string = original_string.encode('utf-8')
print("byte_string: ", type(byte_string), byte_string)
# <class 'bytes'> b'Hello, World!'
# 将字节转换为Base64编码
base64_encoded = base64.b64encode(byte_string).decode('utf-8')
print("Base64编码后的字符串:", type(base64_encoded), base64_encoded)
# Base64编码后的字符串: <class 'str'> SGVsbG8sIFdvcmxkIQ==
将Base64编码的字符串解码为原始字符串
"""
将Base64编码的字符串解码为原始字符串,可以使用base64.b64decode()方法
"""
import base64
# Base64编码后的字符串
base64_string = "SGVsbG8sIFdvcmxkIQ=="
# 将Base64编码的字符串转换为字节
byte_string = base64.b64decode(base64_string)
print("byte_string:" , type(byte_string), byte_string)
# <class 'bytes'> b'Hello, World!'
# 将字节转换为字符串
original_string = byte_string.decode('utf-8')
print("解码后的原始字符串:", type(original_string), original_string)
# <class 'str'> Hello, World!