AppDividend
Latest Code Tutorials

How to Convert Python Bytes to String with Example

0

Python String decode() is an inbuilt method decodes the string using the codec registered for encoding. The decode() function is used to convert from one encoding format, in which argument string is encoded to the desired encoding format.

Convert Python Bytes to String

To convert Python bytes to string, use the decode() method to produce string from a bytes object. The decode() method takes an argument which is the codec and we use utf-8. It can be another codec, but we will use this as this is the standard. It would help if you use utf-8 encoding because it is a very common encoding, but you need to use the encoding your data is actually in.

Syntax

decode(encoding, error)

Parameters

encoding: The encoding parameter is used to define the encoding based on which decoding has to be performed.

error: The error parameter determines how to handle the errors if they occur, e.g., ‘strict’ raises Unicode error.

Return Value

It returns the original string from the decoded string.

Example

To convert from bytes object to a string, follow the below two steps.

Step 1: Convert Original String to a bytes object

This step is only necessary if you don’t have a bytes object. If you have a bytes object, then you don’t need to perform this step.

Let’s first encode the string into a bytes object.

# app.py

str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode()
print(str2)

Output

python3 app.py
b'Hello and welcome to the world of pyth\xc3\xb6n!'

To check the data type of str2, use the type() method.

str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode('utf-8')
print(type(str2))

Output

<class 'bytes'>

You can see that we now have a bytes object. Now, we will convert bytes object to String.

Step 2: Convert from bytes object to String.

To convert bytes object to the original string, use the decode() method with the exact encoding mechanism. We used utf-8 style encoding, so you need to use the same type of decoding as well.

# app.py

str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode('utf-8')
print(type(str2))
print(str2)

print('After converting from bytes to string')
str3 = str2.decode('utf-8')
print(type(str3))
print(str3)

Output

python3 app.py
<class 'bytes'>
b'Hello and welcome to the world of pyth\xc3\xb6n!'
After converting from bytes to string
<class 'str'>
Hello and welcome to the world of pythön!

You can see that the decode() method successfully decodes the bytes object to String.

That is it for Python bytes to string conversion example.

See also

Python List to String

Python Dictionary to String

Python Image to Base64 String

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.