python 3.3 base64

本文介绍如何使用Python的base64模块对字符串进行编码,并演示了处理Unicode字符的具体步骤。首先展示了直接对字符串编码会遇到的类型错误,并给出了正确的编码方式,即先将字符串转换为字节串再进行Base64编码。

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

 

>>> s='我'
>>> base64.b64encode(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python33\lib\base64.py", line 58, in b64encode
    raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str

 

出现上面的错误,就用下面这行。

>>> base64.b64encode(s.encode(encoding='utf-8'))
b'5oiR'

>>> base64.b64encode(s.encode(encoding='utf-8')).decode('utf-8')
'5oiR'

对于\u开头的字符也可以处理了。

>>> str1 = '\u4f60\u597d'

>>> str1.encode(encoding='utf-8').decode()
'你好'
>>>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值