String decode() method in Python
In this tutorial, we will learn about the decode() method used in Python, therefore, we will also see an example to understand this concept of the string decode() method in Python.
What is String decode() method in Python
Decoding is the process of converting code into a format that is useful for any further process. It is the reverse process of Encoding.
But before understanding the concept of decode() it is also important to understand the concept of encode().
encode() is a string method that returns a byte string.
decode() is a byte /string method that returns a (Unicode) string.
This method converts the encoded string and decodes it back to the original string.
encodings: Specifies the type of encoding to be used for decoding.
errors: It handles the errors if present. The default of errors is ‘strict‘. Other examples are ‘ignore’ and ‘replace’.
Note that the sting codec “base64” has been removed from Python 3 and runs properly on Python 2.
To use this in Python 3: import base64
s = input() str1 = s.encode(encoding='IBM039', errors='strict') print("The encoded string in base64 format is : ") print(str1) # printing the original decoded string print("The decoded string is : ") print(str1.decode(encoding='IBM039', errors='strict'))
The encoded string in base64 format is : b'\x97\x81\xa2\xa2\xa6\x96\x99\x84' The decoded string is : password
- In the above example, we are encoding a string and then again decoding it back to the original string.
- But first, encode the entered string to a byte string.
- Now to decode it back, we take the byte string and decode it back to the original string.
- This concept and the above concept can be used for password encryption to prevent any security issues.
You can also read about: string.hexdigits in Python