DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

Python Convert Bytes to String

ItsMyCode |

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. Usingdecode()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))

Enter fullscreen mode Exit fullscreen mode

Output

Before conversion type is <class 'bytes'>
ItsMyCode πŸ•!
Coverted type is <class 'str'>
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Output

Before conversion type is <class 'bytes'>
ItsMyCode πŸ•!
Coverted type is <class 'str'>
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Output

Before conversion type is <class 'bytes'>
ItsMyCode πŸ•!
Coverted type is <class 'str'>
Enter fullscreen mode Exit fullscreen mode

The post Python Convert Bytes to String appeared first on ItsMyCode.

Top comments (2)

Collapse
 
jasonxiong profile image
JasonXiong

The post is so good.

Collapse
 
srinivasr profile image
Srinivas Ramakrishna

Thanks @jasonxiong