Convert Bytes To String In Python

In this post, we will see different techniques for how to convert bytes to string in python. so without wasting any further time. let’s get started.

The string is a sequence of Unicode characters whereas byte is the sequence of bytes. The bytes are machine-readable whereas strings are human-readable.

Learn more about the basics of strings and bytes

1. Convert Bytes To String In Python By Using decode() Method

The decode() method decodes the bytes using the codec registered for encoding. Here is the syntax.

decode(encoding='utf-8', errors='strict') 

encoding : The registered encoding type to decode the bytes.

errors: Use this option for error handling while decoding the bytes. Available options : ‘strict’ (means raise a UnicodeDecodeError), ‘ignore’ (means ignore the error), ‘replace’.

# program to convert bytes to string in python

# Input Bytes
b = b"Hello World"

# convert them to strings by decode method
s = b.decode("utf-8")


Here is the output of the above code.

Output :

ourput of program to convert bytes to string in python

2. By Using str Object

We can also directly convert the bytes to string by using an ‘str’ class. here is what I mean.

b = b'Input Bytes'

s = str(b,"utf-8")

3. Convert String To Bytes In Python

Similarly, we can use encode() method of python string class to convert string to bytes.

# Program to convert string to bytes in python

# input string
s = "Input String"

# Convert to bytes by using encode method
b = s.encode()


b'Input String'

Also read about how to remove characters from the string

Leave a Reply