Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python base64编码

作者:恋你如初   发布日期:2026-01-21   浏览:94

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_string = encode_base64(original_string)
decoded_string = decode_base64(encoded_string)

print(f"Original: {original_string}")
print(f"Encoded: {encoded_string}")
print(f"Decoded: {decoded_string}")

解释说明:

  1. 导入模块:我们首先导入了 base64 模块,该模块提供了对Base64编码和解码的支持。
  2. 编码函数 encode_base64
    • 将输入的字符串编码为字节串(input_bytes)。
    • 使用 base64.b64encode 方法对字节串进行Base64编码。
    • 将编码后的字节串解码为字符串(encoded_string),以便于输出和存储。
  3. 解码函数 decode_base64
    • 将Base64编码的字符串重新编码为字节串(encoded_bytes)。
    • 使用 base64.b64decode 方法对字节串进行解码。
    • 将解码后的字节串解码为原始字符串(decoded_string)。
  4. 示例:展示了如何使用这两个函数对一个字符串进行编码和解码,并打印结果。

上一篇:python r字符串

下一篇:python读取mat文件

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

python中的yield

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站