Why Is Passing Bytes To Class Str Constructor Special?
Solution 1:
The concept behind str
seems to be that it returns a "nicely printable" string, usually in a human understandable form. The documentation actually uses the phrase "nicely printable":
If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).
With that in mind, note that str
of a tuple or list produces string versions such as:
>>> str( (1, 2) )
'(1, 2)'>>> str( [1, 3, 5] )
'[1, 3, 5]'
Python considers the above to be the "nicely printable" form for these objects. With that as background, the following seems a bit more reasonable:
>>> str(b'abc')
"b'abc'"
With no encoding provided, the bytes b'abc'
are just bytes, not characters. Thus, str
falls back to the "nicely printable" form and the six character string b'abc'
is nicely printable.
Post a Comment for "Why Is Passing Bytes To Class Str Constructor Special?"