python3 base64解码_在Python 3 Base64编码

Following this python example , I do:

>>> import base64

>>> encoded = base64.b64encode(b'data to be encoded')

>>> encoded

b'ZGF0YSB0byBiZSBlbmNvZGVk'

But, if I leave out the leading b and do:

>>> encoded = base64.b64encode('data to be encoded')

I get

Traceback (most recent call last):

File "", line 1, in

File "C:\Python32\lib\base64.py", line 56, in b64encode

raise TypeError("expected bytes, not %s" % s.__class__.__name__)

TypeError: expected bytes, not str

Why is this?

解决方案

base64 encoding takes 8-bit binary byte data and encodes it using only the characters A-Z, a-z and 0-9, so it can be transmitted over channels that does not preserve all 8-bits of data, such as email.

Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

In your second example:

>>> encoded = base64.b64encode('data to be encoded')

All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

>>> encoded = 'data to be encoded'.encode('ascii')

Or simpler:

>>> encoded = b'data to be encoded'

Which would be the same thing in this case.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值