python2和python3中的編碼問題


開始拾起python,准備使用python3, 造輪子的過程中遇到了編碼的問題,又看了一下python3和python2相比變化的部分。

首先說個概念:

 unicode:在本文中表示用4byte表示的unicode編碼,也是python內部使用的字符串編碼方式。

  

utf-8:在本文中指最少1byte表示的unicode編碼方式

我在使用

if isinstance(key,unicode):

    key= key.encode('utf-8')

的時候,發現key值被轉成了b'foo',b'bar' 這種類型。於是查了一下。

對於python2,內置的字符串類型有str和unicode。比如'abc'是str,u'你好'則是unicode。

python3里沒有預定義unicode類型,內置的字符串就是str,因此使用isinstance(key,unicode)的時候會報錯,python3 renamed the unicode type to str,the old str type has been replaced by bytes。

對於python2和python3下的encode如下

python3:

python2:

可以看到python3編碼后的格式變成了bytes類型。

另一個關於字典里items和iteritems的變化也要注意:

python docs里說:

dict.items(): Return a copy of the dictionary’s list of (key, value) pairs.

dict.iteritems(): Return an iterator over the dictionary’s (key, value) pairs.

在python3里移除了iteritems方法,使用items()代替它返回一個view,which is pretty much like iterator,即items()就返回一個類似集的容器對象,而不是一個列表,如果想要返回一個列表需要list(dict.items()).

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM