How to Convert Bytes to String in Python

There are many methods to convert bytes to string in Python . Here is one of the method:

decode() method

The decode() method in Python converts a bytes  into a string. The argument string is encoded using this method, which converts it to the specified encoding scheme from one encoding scheme. In contrast to the encode, this functions. In order to decode the encoding string, it accepts its encoding and returns the original string.

Here is the syntax for decode() method:

syntax: decode(encoding, error)

there are three parameters:

  • Encoding: Describes the encoding that must be used as the foundation for decoding.
  • Error: Chooses how to respond to mistakes when they happen. For example, “strict” raises a Unicode error in the event of exception, whereas “ignore” chooses to ignore the errors.
  • Returns: From the encoded string, the original string is returned.

working of Decode() method

 

ENCODE AND DECODE A STRING IN PYTHON

 

The below given code is the example for decode() method:

# initializing string 
String = "codespeedycode"
  
encoded_string = String.encode('utf-8') 
print('The encoded string in base64 format is :') 
print(encoded_string) 
  
decoded_string = encoded_string.decode('utf-8') 
print('The decoded string is :') 
print(decoded_string) 


output:
The encoded string in base64 format is : 
b'codespeedycode'
The decoded string is : 
codespeedycode

Using Python’s decode() function to convert bytes to a string is a typical task, particularly when working with data that is read from files or received via networks. Let’s say you have a byte object b’\x48\x67\x6c\x6c\x6f’ that encodes the string “WELCOME” in UTF-8. Using the UTF-8 encoding, you would use the decode() function to convert these bytes into a string: decoded string = b’\x48\x65\x6c\x6c\x6f’.decode(‘utf-8’). The Unicode string “WELCOME” will be present in decoded string following this procedure. You can guarantee that the bytes are interpreted correctly and that the intended characters are preserved without running into decoding issues by providing the correct encoding throughout the decoding process.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top