python - Python 中的字节总是八位字节吗?

标签 python language-lawyer jython pypy micropython

是否存在断言失败的 Python 实现:

assert all(byte in range(256) for byte in any_bytes_object) # Python 3 semantics 
assert all(byte in range(256) for byte in map(ord, any_bytes_object)) # Python 2

POSIX specifies explicitly that CHAR_BIT == 8 (8 bits per byte) . Python 中有类似的保证吗?它是否记录在某处?

Python 2 reference says: "Characters represent (at least) 8-bit bytes."

如果 bytes 名称未定义(在旧的 Python 版本上),例如在 Jython 2.5 上,那么问题是关于 str 类型(bytestrings),即 bytes = str 在 Python 2 上。

最佳答案

字节对象 Python 3 documentation

bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256

bytearray 类型在 Python 3 中均有记录。和 Python 2作为

a mutable sequence of integers in the range 0 <= x < 256

所以语言是在8位字节的假设下设计的。


Python 2 数据模型部分说“至少”8 位,这似乎只是 Python 2 文档与 Python 3 文档相比没有及时更新的地方之一。它至少可以追溯到Python 1.4 ,早在他们不确定是否要支持奇怪的字节大小的早期。

自从至少在 2.0 版本中引入了 unicode 支持以来,文档中到处都是将 bytestring 类型称为“8 位字符串”。 Python 不像 C 那样严格指定,但我认为 Python 2.0 或更高版本的任何“符合”实现都必须具有 8 位字节。

关于python - Python 中的字节总是八位字节吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36265726/

相关文章:

hadoop - 如何在 Pig 的 Jython UDF 中增加 Hadoop 计数器

jython - 为什么使用 "\"在 jython 中显示错误

python - 如何通过 python input() 函数传递空列表

python - 正则表达式中两个字符之间的边界字符串

python - multiprocessing.Pool 生成的进程多于仅在 Google Cloud 上请求的进程

c - 调用自身的宏打印自身?

java - 通过 Java ScriptEngine 在 JavaScript 中使用 jar

python - 从子线程 python 中杀死 main thead

javascript - 在 for 循环的初始化表达式中声明的变量是否总是词法在体内

c++ - 为什么 std::array 没有运算符 T*?