Python Strings () decode method



decode () — this is the method specified in Strings in Python 2.
This method is used to convert from a single encoding scheme where the argument string is encoded to the desired encoding scheme. This works the opposite of encoding. It takes the encoding of the encoding string to decode it and returns the original string.

Syntax: decode (encoding, error)

Parameters:
encoding: Specifies the encoding on the basis of which decoding has to be performed.
error: Decides how to handle the errors if they occur, eg `strict` raises Unicode error in case of exception and `ignore` ignores the errors occurred.

Returns: Returns the original string from the encoded string.

Code # 1: Code to decode a string

# Python code for demo
# decode ()

 
# initialization string

str = "pythonengineering"

 
# encoding string

str_enc = str . encode ( `base64` , ` strict` )

 
# print the encoded string

print "The encoded string in base64 format is:" ,

print str_enc

 
# print the original decoded strings

print "The decoded string is: " ,

print str_enc. decode ( `base64` , ` strict` )

Output:

 The encoded string in base64 format is: Z2Vla3Nmb3JnZWVrcw == The decoded string is: pythonengineering 

Application:
Joint encoding and decoding can be used in a simple backend password storage application and in many other applications such as cryptography, which is concerned with keeping information confidential. 
A short demonstration of the use of a password is shown below.

Code # 2: Code to demonstrate the use of encoding and decoding

# Python code to showcase
# apply encoding

 
# user input
# user = raw_input ()
# pass = raw_input ()

 

user = " pythonengineering "

passw = "i_lv_coding"

 
# convert password to encoders ku base64

passw = passw.encode ( `base64` , ` strict` )

 
# user input
# user_login = raw_input ()
# pass_login = raw_input ()

 

user_login = "pythonengineering"

 
# incorrect password

pass_wrong = "pythonengineering"

 

print " P assword entered: " + pass_wrong

  

if (pass_wrong = = passw.decode ( `base64` , ` strict` )):

  print " You are logged in !! "

else print "Wrong Password !! "

  

print ` `

  
# correct password

pass_ right = "i_lv_coding"

 

print "Password entered:" + pass_right

 

if (pass_right = = passw.decode ( `base64` , ` strict ` )):

  print "You are logged in !!"

else print "Wrong Password !!"

Output:

Password entered: pythonengineering Wrong Password !! Password entered: i_lv_coding You are logged in !!