Thursday, December 26, 2024
Google search engine
HomeLanguagesPython Strings decode() method

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.

Python Decode() Function Syntax

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, e.g ‘strict’ raises Unicode error in case of exception and ‘ignore’ ignores the errors occurred. 
  • Returns : Returns the original string from the encoded string.

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 = "neveropen"
  
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'neveropen'
The decoded string is : 
neveropen

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 = "neveropen"
passw = "i_lv_coding"
  
# Converting password to base64 encoding
passw_encoded = base64.b64encode(passw.encode('utf-8')).decode('utf-8')
  
user_login = "neveropen"
  
# Wrongly entered password
pass_wrong = "neveropen"
  
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 : neveropen
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:

RELATED ARTICLES

Most Popular

Recent Comments