Encode and Decode a String in Python
The above code is an example of encoding and decoding. Here first we encoded the string using UTF-8 and then decoded it which gives the same output String as we give it in input.
Python3
# initializing string String = "w3wiki" 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'w3wiki'
The decoded string is :
w3wiki
Application of Encode-Decode
Encoding and decoding together can be used in the simple applications of storing passwords in the back end and many other applications like cryptography which deals with keeping information confidential. A small demonstration of the password application is depicted below.
Python3
import base64 user = "w3wiki" passw = "i_lv_coding" # Converting password to base64 encoding passw_encoded = base64.b64encode(passw.encode( 'utf-8' )).decode( 'utf-8' ) user_login = "w3wiki" # Wrongly entered password pass_wrong = "w3wiki" print ( "Password entered:" , pass_wrong) if pass_wrong = = base64.b64decode(passw_encoded).decode( 'utf-8' ): print ( "You are logged in!" ) else : print ( "Wrong Password!" ) print () # Correctly entered password pass_right = "i_lv_coding" print ( "Password entered:" , pass_right) if pass_right = = base64.b64decode(passw_encoded).decode( 'utf-8' ): print ( "You are logged in!" ) else : print ( "Wrong Password!" ) |
Output:
Password entered : w3wiki
Wrong Password!!
Password entered : i_lv_coding
You are logged in!!
Working of the Python Decode() Method?
The following flowchart shows the working of Python decoding:
Python Strings decode() method
In Python we have decode() is a method specified in Strings. This method is used to convert from one encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.