How to use decode() Function in Python with Example?

The `decode()` function in Python is used to convert bytes into a string. This function is often used when you have data in bytes format (like from a file or a network socket) and you want to convert it into a human-readable string.

Basic Syntax

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

Here’s an example:

Example:

Suppose you have a bytes object, and you want to decode it into a string using UTF-8 encoding.

# A bytes object
byte_data = b'Hello, World!'
# Decoding the bytes to a string using UTF-8 encoding
decoded_string = byte_data.decode('utf-8')
# Printing the result
print(decoded_string)

Output:

Hello, World!

Explanation:

– `b’Hello, World!’` is a bytes object.
– `.decode(‘utf-8’)` converts this bytes object into a string using UTF-8 encoding, which is a common encoding format.

If the bytes were encoded using a different format, you would need to specify the appropriate encoding in the `decode()` function.