日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

作者:檸 檬沒我萌 更新時間: 2022-02-19 編程語言

在這里插入圖片描述出現這個問題可能是兩個原因造成的:
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,就是吧一堆機器認識的,解釋為人能讀懂的

原文鏈接:https://blog.csdn.net/qq_43192819/article/details/108981008

欄目分類
最近更新