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'>

0 Shares
Leave a Reply

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

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…