Python Convert Bytes to String

In this tutorial, we will take a look at how to convert bytes to string in Python. 

We can convert bytes to string using the below methods 

  1. Using decode() method
  2. Using str() method
  3. Using codecs.decode() method

Method 1: Using decode() method

The bytes class has a decode() method. It takes the byte object and converts it to string. It uses the UTF-8 encoding by default if you don’t specify anything. The decode() method is nothing but the opposite of the encode.

# Python converting bytes to string using decode()

data = b'ItsMyCode \xf0\x9f\x8d\x95!'
print(data)
print("Before conversion type is", type(data))

# coversion happens from bytes to string
output = data.decode()
print(output)
print("Coverted type is ", type(output))

Output

Before conversion type is <class 'bytes'>
ItsMyCode 🍕!
Coverted type is  <class 'str'>

Method 2: Using str() function

Another easiest way to convert from Bytes to string is using the str() method. You need to pass the correct encoding to this method else it will lead to incorrect conversion.

# Python converting bytes to string using str()

data = b'ItsMyCode \xf0\x9f\x8d\x95!'
print(data)
print("Before conversion type is", type(data))

# coversion happens from bytes to string
output = str(data,'UTF-8')
print(output)
print("Coverted type is ", type(output))

Output

Before conversion type is <class 'bytes'>
ItsMyCode 🍕!
Coverted type is  <class 'str'>

Method 3: Using codecs.decode() method

codecs module comes as a standard built-in module in Python, and it has a decode() method which takes the input bytes and returns the string as output data.

# Python converting bytes to string using decode()
import codecs

data = b'ItsMyCode \xf0\x9f\x8d\x95!'
print(data)
print("Before conversion type is", type(data))

# coversion happens from bytes to string
output = codecs.decode(data)
print(output)
print("Coverted type is ", type(output))

Output

Before conversion type is <class 'bytes'>
ItsMyCode 🍕!
Coverted type is  <class 'str'>
Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Numpy.repeat() Function

numpy.repeat() Function

Table of Contents Hide SyntaxRepeat ParametersReturn ValueExample 1: Repeating the Single-Dimensional NumPy ArrayExample 2: Repeating the Two-Dimensional NumPy ArrayExample 3: Repeating the NumPy Array Row WiseExample 4: Repeating the NumPy…
View Post