開始拾起python,準備使用python3, 造輪子的過程當中遇到了編碼的問題,又看了一下python3和python2相比變化的部分。python
首先說個概念:編碼
unicode:在本文中表示用4byte表示的unicode編碼,也是python內部使用的字符串編碼方式。
utf-8:在本文中指最少1byte表示的unicode編碼方式
我在使用code
if isinstance(key,unicode): key= key.encode('utf-8')
的時候,發現key值被轉成了b'foo',b'bar' 這種類型。因而查了一下。對象
對於python2,內置的字符串類型有str和unicode。好比'abc'是str,u'你好'則是unicode。blog
python3裏沒有預約義unicode類型,內置的字符串就是str,所以使用isinstance(key,unicode)的時候會報錯,python3 renamed the unicode type to str,the old str type has been replaced by bytes。utf-8
對於python2和python3下的encode以下unicode
python3:字符串
python2:it
能夠看到python3編碼後的格式變成了bytes類型。io
另外一個關於字典裏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()).