为什么base64.b64encode()返回字节对象? [英] Why does base64.b64encode() return a bytes object?
问题描述
base64.b64encode()
的目的是将二进制数据转换为ASCII安全的文本".但是,该方法返回一个字节类型的对象:
The purpose of base64.b64encode()
is to convert binary data into ASCII-safe "text". However, the method returns an object of type bytes:
>>> import base64
>>> base64.b64encode(b'abc')
b'YWJj'
简单地获取该输出并decode()
很容易,但是我的问题是:base64.b64encode()
返回bytes
而不是str
的意义是什么?
It's easy to simply take that output and decode()
it, but my question is: what is a significance of base64.b64encode()
returning bytes
rather than a str
?
推荐答案
base64.b64encode()函数的目的是将二进制数据转换为ASCII安全的文本"
The purpose of the base64.b64encode() function is to convert binary data into ASCII-safe "text"
Python对此表示不同意见-base64被故意分类为二进制转换.
Python disagrees with that - base64 has been intentionally classified as a binary transform.
这是Python 3中的一项设计决策,即强制字节和文本分开并禁止隐式转换. Python现在对此非常严格,以致bytes.encode
甚至都不存在,因此b'abc'.encode('base64')
会引发AttributeError
.
It was a design decision in Python 3 to force the separation of bytes and text and prohibit implicit transformations. Python is now so strict about this that bytes.encode
doesn't even exist, and so b'abc'.encode('base64')
would raise an AttributeError
.
该语言的观点是字节串对象已经被编码了.将字节编码为文本的编解码器不适合此范例,因为当您要从字节域转到文本域时,它是一个 decode .请注意,rot13
编码也已从标准编码的列表中消失出于相同的原因-它不适合Python 3范例.
The opinion the language takes is that a bytestring object is already encoded. A codec which encodes bytes into text does not fit into this paradigm, because when you want to go from the bytes domain to the text domain it's a decode. Note that rot13
encoding was also banished from the list of standard encodings for the same reason - it didn't fit properly into the Python 3 paradigm.
还有一个性能参数:假设Python自动处理base64输出的解码,这是C代码从
There also can be a performance argument to make: suppose Python automatically handled decoding of the base64 output, which is an ASCII-encoded binary representation produced by C code from the binascii
module, into a Python object in the text domain. If you actually wanted the bytes, you would just have to undo the decoding by encoding into ASCII again. It would be a wasteful round-trip, an unnecessary double-negation. Better to 'opt-in' for the decode-to-text step.
这篇关于为什么base64.b64encode()返回字节对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!