Python 3.x 中Base64的使用

本文详细介绍了如何使用Python的base64模块进行字符串的编码与解码操作,包括将汉字转换为base64编码,以及如何将base64编码的字符串解码回原始的汉字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
import base64


str = "你好"
encodestr = base64.b64encode(str.encode('utf-8'))
print(encodestr)
b'5L2g5aW9'     # 输出结果

# 可以看到,输出的结果被包含在 b' '中,表示byte字节,为了方便使用,我们使用下面的方法对其进行解码,直接得到字符串

encodestr2 = base64.b64encode(str.encode('utf-8')).decode('utf-8')
print(encodestr2)
5L2g5aW9        # 输出结果

decodestr = base64.b64decode(encodestr2.encode('utf-8'))
print(decodestr)
b'\xe4\xbd\xa0\xe5\xa5\xbd'     # 输出结果

# 同理,我们使用下面的方法对其进行解码,直接得到字符串

decodestr2 = base64.b64decode(encodestr2.encode('utf-8')).decode('utf-8')
print(decodestr2)
你好                            # 输出结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值