Say I have a variable containing bytes:
>>> a = b'Hello World'
It can be verified with:
>>> type(a)
<class 'bytes'>
Now I try and convert a into a string with str():
>>> b = str(a)
and sure enough it is a string:
>>> type(b)
<class 'str'>
Now I try and print b but I get a totally unexpected result:
>>> print(b)
b'Hello World'
It returns a string, as I would expect but also it keeps the b (byte symbol) and the ' (quotation marks).
Why does it do this, and not just print the message between the quotation marks?
Don't think of a bytes value as a string in some default 8-bit encoding. It's just binary data. As such, str(a) returns an encoding-agnostic string to represent the value of the byte string. If you want 'Hello World', be specific and decode the value.
>>> b = a.decode()
>>> type(b)
>>> str
>>> print(b)
Hello World
In Python 2, the distinction between bytes and text was blurred. Python 3 went to great lengths to separate the two: bytes for binary data, and str for readable text.
For another perspective, compare
>>> list("Hello")
['H', 'e', 'l', 'l', 'o']
with
>>> list(b"Hello")
[72, 101, 108, 108, 111]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With