Print Bytes without b in Python

Just as a string is a collection of Unicode characters in Python 3, bytes are a collection of objects. Bytes can be stored on a disk and internally everything is stored as bytes in a computer. The relation between strings and bytes is that a string can be encoded into a bytes object.

To make such conversions we can use the encode() function and specify the encoding type like ASCII, UTF-16, and more in the same.

A lot of times, we have seen the use of the b prefix in defining bytes. This prefix is used to convey to the interpreter to create a byte string literal and Python 3 displays it following the ASCII encoding. We can also use the codes that get converted to the respected character using the escape sequences.

For example,

Output:

b’A’

In the above example, we created a byte string literal and displayed it. Notice the prefix b in the output as well.

The same is not done in Python 2, because in Python 2 the bytes are an alias to the string. The change of a string being a collection of Unicode characters was done in Python 3.

Ways to Print Bytes without b in Python

In this tutorial, we will discuss how to print bytes without b in Python.

Using the decode() Function to Print Bytes without b in Python

The decode() function is used to decode the encoded byte string to a normal string of Unicode characters. This way, the final result does not contain the b prefix.

For example,

Output:

A

Using the str() Function to Print Bytes without b in Python

For UTF-8 compatible data, we can use the str() function to convert the bytes to a string. This will remove the prefix from the bytes object.

For example,

Output:

A

Using the repr() Function to Print Bytes without b in Python

The repr() function is similar to the str() constructor in Python. We can use it to get a string representation of different objects. For a byte object, the repr() function invokes the internal bytes.__repr__ magic method.

It returns the bytes object as a string and we can manually slice off the prefix b from the same.

See the code below.

Output:

‘A’

Conclusion

This tutorial demonstrated several methods to print bytes without b in Python. We started the article with the generic definition of a bytes object in Python 3 and its relation with a string. We also highlighted how this object was the same as the string in Python 2.

The methods to print bytes without b in Python mainly followed the same approach of decoding the bytes object using the decode(), str, and repr functions. The only additional thing in the final function was that we had to slice off the b prefix manually after decoding the data.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *