What's the rationale for b"..." in this example?

Ben Finney ben+python at benfinney.id.au
Tue May 15 13:28:18 EDT 2018


Skip Montanaro <skip.montanaro at gmail.com> writes:

> Consider this:
>
> >>> bytes("abc", encoding="utf-8")
> b'abc'
>
> Looks reasonable. Then consider this:
>
> >>> str(bytes("abc", encoding="utf-8"))
> "b'abc'"
>
> Why is the b'...' bit still there?

Because the bytes object is asked for a text representation of itself,
and the text value ‘b'abc'’ is what it returned.

> I suppose it's because I didn't tell it explicitly how to decode the
> bytes object, as when I do, I get the expected result:
>
> >>> str(bytes("abc", encoding="utf-8"), encoding="utf-8")
> 'abc'

Yes.

> Coming from a still largely Python 2 perspective, did all attempts to
> apply default encodings disappear in Python 3?

To the extent I understand that question, the answer is no.

Rather, the ‘bytes’ and ‘str’ types are now entirely incompatible, and
implicit conversions are never done between them. Any conversions
between them must be explicit.

-- 
 \            “There are always those who think they know what is your |
  `\          responsibility better than you do.” —Ralph Waldo Emerson |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list