Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

Convert bytes to a string in Python 3

Solution:

In Python 3, you can convert bytes to a string using the decode() method.

What’s that? The decode() method interprets the bytes as a sequence of Unicode code points and returns a string.

You need to specify the encoding that was used to encode the bytes. Common encodings include 'utf-8', 'utf-16', 'latin-1', etc.

Let’s take an example.


#Example bytes 
byte_data = b'Hello, World!'

#Convert bytes to string using decode() method 
string_data = byte_data.decode(utf-8)

#Print the result 
print(string_data)

In this example, the decode('utf-8') method is used because 'utf-8' is a widely used encoding for text in Python. Check out more about Python programming in our blogs!