开始拾起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()).