Python的字节对象也被称为字符串吗?

2024-04-25 06:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这是Dive Into Python 3中有关字符串的部分:

In Python 3, all strings are sequences of Unicode characters. There is no such thing as a Python string encoded in utf-8, or a Python string encoded as CP-1252. “Is this string utf-8?” is an invalid question. utf-8 is a way of encoding characters as a sequence of bytes. If you want to take a string and turn it into a sequence of bytes in a particular character encoding, Python 3 can help you with that. If you want to take a sequence of bytes and turn it into a string, Python 3 can help you with that too. Bytes are not characters; bytes are bytes. Characters are an abstraction. A string is a sequence of those abstractions.

今天早些时候,我使用了hashlib模块,并阅读了md5的帮助文本,内容是:

Return a new MD5 hash object; optionally initialized with a string.

好吧,它不接受string-它接受一个bytes对象。在

也许我读得太多了,但是如果应该使用帮助文本中声明的bytes来代替它,会不会更有意义呢?或者人们对字符串和字节使用相同的名称?在


Tags: of字符串inyouanstringbytesis
2条回答

可能是Python留下的帮助。在

这是从2到3的较大变化之一

    Python2          Python3

    str              bytes
    unicode          str

Python2.6+通过使bytes成为str的同义词,开始为更改做准备

你应该把它报告给开发者(除非它已经被修复了——我这里只有3.1.2)。我认为措辞应该改进一下

在Python2和3中,str既用于字符串,也用于字节。实际上,在Python2.6之前,甚至没有bytes类型(在2.6和2.7中,bytes is str)。在

hashlib文档中提到的不一致是这个历史的产物。在

相关问题 更多 >