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'
2

1 Answer 1

4

The Python 3 bytes constructor takes an optional int parameter specifying the number of bytes to output. All bytes are initialized to 0 (\x00) with that constructor, so bytes(1) == b'\x00'.

The Python 2 bytes constructor is identical to str, and therefore just stringizes its argument:

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
Sign up to request clarification or add additional context in comments.

2 Comments

What is the purpose of bytes() in Python 2 if it is synonymous with str()?
@Brian: I guess it is for some measure of similarity with Python3, but clearly it causes confusion...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.