2

I got curious after the discussion taking place on this question. It appears that the behavior of bytes() has changed in python3. In the docs for py3 it is now listed as a built-in function that behaves the same as bytearray() except for the result being immutable. It doesn't appear in the same place in py2 docs.

In digging thru the docs for a while I couldn't really find anything detailing what's changed from 2 to 3, but it looks like something definitely has. What's the difference and why was it changed?

From the linked question in the comments someone remarked with respect to py3

bytes(1) returns b'00'

but in 2.7.5

>>> bytes(1)
'1'
4

1 回答 1

4

Python 3bytes构造函数采用一个可选int参数,指定要输出的字节数。使用该构造函数将所有字节初始化为 0 ( \x00),因此bytes(1) == b'\x00'.

Python 2bytes构造函数与 相同str,因此只是将其参数字符串化:

Python 2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes is str
True
于 2013-09-04T15:22:52.480 回答