How to print a String without the b’ prefix for bytes in Python

To print a String without the b’ prefix for bytes in Python, you can use the str(), decode(), or repr() functions. Follow the information below for detailed instructions.

How to print a string without the b’ prefix for bytes in Python

Using the str() function

You can use the str() function to print a string without the b’ prefix for bytes in Python. Simply, you assign the first parameter as the byte object, and the encoding is ‘utf-8’.

Look at the example below.

# Create a byte.
byte_value = b'Learn Share IT'
print(byte_value)
print('Type: {}\n'.format(type(byte_value)))

# Create a String without the b' prefix with the str() function.
string = str(byte_value, encoding='utf-8')
print(string)
print('Type: {}'.format(type(string)))

Output

b'Learn Share IT'
Type: <class 'bytes'>

Learn Share IT
Type: <class 'str'>

Using the decode() function

Besides the str() function, you can print a String without the b’ prefix for bytes in Python with the decode() function. This function is used to convert the byte object to the String. So the b’ prefix will be removed by this function.

Look at the example below.

# Create a byte.
byte_value = b'Learn Share IT'
print(byte_value)
print('Type: {}\n'.format(type(byte_value)))

# Create a String without the b' prefix with the decode() function.
string = byte_value.decode()
print(string)
print('Type: {}'.format(type(string)))

Output

b'Learn Share IT'
Type: <class 'bytes'>

Learn Share IT
Type: <class 'str'>

Using the repr() function

In addition, you can use the repr() function to print a String without the b’ prefix for bytes in Python. Unlike the str() and decode() functions, this function can not remove the b’ prefix directly. We have to convert the current byte to the String with the repr() function first. Then, we can get the result by slicing this String.

Look at the example below to learn more about this solution.

# Create a byte.
byte_value = b'Learn Share IT'
print(byte_value)
print('Type: {}\n'.format(type(byte_value)))

# Convert the byte object to a String.
string = repr(byte_value)

# Remove the b' prefix of this String.
string = string[2:-1]
print(string)
print('Type: {}'.format(type(string)))

Output

b'Learn Share IT'
Type: <class 'bytes'>

Learn Share IT
Type: <class 'str'>

Summary

We have shown you how to print a String without the b’ prefix for bytes in Python in 3 ways. From our point of view, you should use the str() or decode() functions in this case because you can get the desired result with one step. If you have any questions about this tutorial, leave your comment below. Thanks!

Leave a Reply

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