1. 程式人生 > >python中decode()函式函式的用法

python中decode()函式函式的用法

python字串函式用法大全連結

decode()函式

描述:以 encoding 指定的編碼格式解碼字串,預設編碼為字串編碼。

  • encoding ——要使用的編碼,如:utf-8,gb2312,cp936,gbk等。

  • errors ——設定不同解碼錯誤的處理方案。預設為 'strict',意為編碼錯誤引起一個 UnicodeDecodeError。 其它可能得值有 'ignore', 'replace'以及通過 codecs.register_error() 註冊的1其它值。

語法:str.decode(encoding='utf-8', errors='strict')

程式示例:

s = "我愛祖國"
str1 = s.encode(encoding="utf-8",errors="strict")
str2 = s.encode("gb2312") #編碼錯誤的處理方案預設為"strict"
str3 = s.encode("gbk")
print(str1.decode(encoding="utf-8",errors="strict"))#用utf-8的解碼格式,解碼str1.
print(str1.decode(encoding="gbk",errors="ignore"))##如果以gbk的解碼格式對str1進行解碼得,將無法還原原來的字串內容
print(str1.decode(encoding="gbk",errors="strict"))
print(str1.decode(encoding="gbk",errors="replace"))
print("\n")
print(str2.decode("gb2312"))
print(str3.decode("gbk"))

程式執行結果:

我愛祖國
鎴戠埍紲栧浗
鎴戠埍紲栧浗
鎴戠埍紲栧浗


我愛祖國
我愛祖國

注:在python中encodedecode分別指編碼和解碼