python中encode和decode使用講解與演示

 1.基本語法

1.encode()和decode()都是字符串的函數

      decode解碼             encode編碼
str ---------> str(Unicode,byte類型) ---------> str

  2.decode()與encode()方法可以接受參數,其聲明分別爲:

 其中的encoding是指在解碼編碼過程中使用的編碼(此處指“編碼方案”是名詞),errors是指錯誤的處理方案。

bytes.decode(encoding="utf-8", errors="strict")
str.encode(encoding="utf-8", errors="strict")

3.查看官網關於encode與decode方法的使用說明如下:

1.str.encode(encoding="utf-8"errors="strict")

Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore''replace''xmlcharrefreplace','backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

2.bytes.decode(encoding="utf-8"errors="strict")

Return a string decoded from the given bytes. Default encoding is 'utf-8'errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore''replace' and any other name registered viacodecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

2.使用演示與注意事項


a = '編碼測試'

#使用不同的編碼格式給a進行編碼
b = a.encode('utf-8')
c = a.encode('gb2312') #發現gb2312和gbk結果一樣
d = a.encode('gbk')
print(type(b),b)
print(type(c),c)
print(type(d),d)
'''
<class 'bytes'> b'\xe7\xbc\x96\xe7\xa0\x81\xe6\xb5\x8b\xe8\xaf\x95'
<class 'bytes'> b'\xb1\xe0\xc2\xeb\xb2\xe2\xca\xd4'
<class 'bytes'> b'\xb1\xe0\xc2\xeb\xb2\xe2\xca\xd4'
'''
#使用不同的解碼方式解碼
b1 = b.decode('utf-8')
c1 = c.decode('gb2312')
d1 = d.decode("gbk")
b11 = b.decode('gbk')  #b本來是用utf-8編碼,現在用gbk進行解碼,出現亂碼的情況
print(type(b1),b1)
print(type(c1),c1)
print(type(d1),d1)
print(type(b11),b11)  #b本來是用utf-8編碼,現在用gbk進行解碼,出現亂碼的情況
'''
<class 'str'> 編碼測試
<class 'str'> 編碼測試
<class 'str'> 編碼測試
<class 'str'> 緙栫爜嫺嬭瘯
'''
  • 字符串通過編碼成爲字節碼,字節碼通過解碼成爲字符串。 
  • 字符串或者字節只能同時擁有一個方法 ,要麼解碼要麼編碼

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章