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

Ethan Furman ethan at stoneleaf.us
Tue May 15 12:27:39 EDT 2018


On 05/15/2018 08:14 AM, Skip Montanaro wrote:
> 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 you are printing a bytes object, not a str.
> 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'
>> Coming from a still largely Python 2 perspective, did all attempts to apply
> default encodings disappear in Python 3?

Pretty much, yup. There is no more guessing what encoding to use -- either specify it, or be made aware that you 
printed a bytes object.
--
~Ethan~


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /