Python字符串 decode() 方法
decode() 是Python 2 中 Strings 中指定的方法。
此方法用于从一种编码方案转换,其中参数字符串被编码为所需的编码方案。这与编码相反。它接受编码字符串的编码对其进行解码并返回原始字符串。
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.
代码#1:解码字符串的代码
# Python code to demonstrate
# decode()
# initializing string
str = "geeksforgeeks"
# encoding string
str_enc = str.encode(encodeing='utf8')
# printing the encoded string
print ("The encoded string in base64 format is : ",)
print (str_enc )
# printing the original decoded string
print ("The decoded string is : ",)
print (str_enc.decode('utf8', 'strict'))
输出:
The encoded string in base64 format is : Z2Vla3Nmb3JnZWVrcw==
The decoded string is : geeksforgeeks
应用 :
编码和解码可以一起用于在后端存储密码的简单应用程序和许多其他应用程序,如处理信息保密的密码学。
密码应用程序的一个小演示如下所示。
代码 #2:演示编码解码应用的代码
# Python code to demonstrate
# application of encode-decode
# input from user
# user = input()
# pass = input()
user = "geeksforgeeks"
passw = "i_lv_coding"
# converting password to base64 encoding
passw = passw.encode('base64', 'strict')
# input from user
# user_login = input()
# pass_login = input()
user_login = "geeksforgeeks"
# wrongly entered password
pass_wrong = "geeksforgeeks"
print ("Password entered : " + pass_wrong )
if(pass_wrong == passw.decode('base64', 'strict')):
print ("You are logged in !!")
else : print ("Wrong Password !!")
print( '\r')
# correctly entered 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 !!")
输出:
Password entered : geeksforgeeks
Wrong Password!!
Password entered : i_lv_coding
You are logged in!!