import base64
# 将字符串编码为base64
def encode_base64(input_string):
# 将输入字符串编码为字节串
input_bytes = input_string.encode('utf-8')
# 使用base64编码
encoded_bytes = base64.b64encode(input_bytes)
# 将编码后的字节串解码为字符串
encoded_string = encoded_bytes.decode('utf-8')
return encoded_string
# 将base64编码的字符串解码为原始字符串
def decode_base64(encoded_string):
# 将输入字符串编码为字节串
encoded_bytes = encoded_string.encode('utf-8')
# 使用base64解码
decoded_bytes = base64.b64decode(encoded_bytes)
# 将解码后的字节串解码为字符串
decoded_string = decoded_bytes.decode('utf-8')
return decoded_string
# 示例
original_string = "Hello, World!"
encoded = encode_base64(original_string)
decoded = decode_base64(encoded)
print(f"Original: {original_string}")
print(f"Encoded: {encoded}")
print(f"Decoded: {decoded}")
base64
模块来进行编码和解码操作。encode_base64
):encode('utf-8')
)。base64.b64encode
进行编码,得到编码后的字节串。decode('utf-8')
),以便于输出和存储。decode_base64
):base64.b64decode
进行解码,得到解码后的字节串。希望这段代码和解释对你有帮助!
上一篇:python变量名
下一篇:return在python中用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站