gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:37:13 27 4
gpt4 key购买 nike

这是来自 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 不是更有意义吗?还是人们对字符串和字节使用相同的名称?

最佳答案

在 Python 2 和 3 中,str 既用于字符串也用于字节。事实上,在 Python 2.6 之前,甚至没有 bytes 类型(在 2.6 和 2.7 中,bytes 是 str)。

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

关于python - Python 的字节对象也称为字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7032427/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com