Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting bytes to string with str() returns string with speech marks

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?

like image 529
Xantium Avatar asked Sep 29 '26 09:09

Xantium


1 Answers

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]
like image 52
chepner Avatar answered Oct 01 '26 23:10

chepner