1. 程式人生 > 實用技巧 >AttributeError: ‘str‘ object has no attribute ‘decode‘解決方法

AttributeError: ‘str‘ object has no attribute ‘decode‘解決方法

在這裡插入圖片描述出現這個問題可能是兩個原因造成的:
1、Python2和Python3在字串編碼上的區別。
2、Python 3.4: str : AttributeError: ‘str’ object has no attribute 'decode
原因一的解決方法:
print (‘張俊’.encode(‘utf-8’). decode(‘utf-8’) ) #必須將位元組字串解碼後才能打印出來
參考連結:https://www.cnblogs.com/geekard/archive/2012/10/04/python-string-endec.html
原因二的解決方法:各種編碼方式嘗試解決:utf-8,gbk,ISO-8859-1,gb2312

原因一才是主要原因,主要解決方法。
在這裡插入圖片描述
AttributeError: ‘str’ object has no attribute ‘decode’
一般是因為str的型別本身不是bytes,所以不能解碼

兩個概念:
普通str:可理解的語義
位元組流str(bytes)(0101010101,視覺化顯示)

兩個語法
Encode: 把普通字串 轉為 機器可識別的bytes
Decode: 把bytes轉為字串

兩個差異
Python3的str 預設不是bytes,所以不能decode,只能先encode轉為bytes,再decode
python2的str 預設是bytes,所以能decode

一個結論


所以str.decode 本質是bytes型別的str的decode
python3經常出現 AttributeError: ‘str’ object has no attribute ‘decode’

非要這樣玩,只能先encode轉為bytes,再decode
強制轉換忽略錯誤:
bytes.decode(‘’utf-8‘’, ‘’ignore‘’)

記憶小技巧
編碼就是encode,把你認識的轉為,機器人認識的
解碼decode,就是吧一堆機器認識的,解釋為人能讀懂的