红联Linux门户
Linux帮助

python2和python3中的编码问题

发布时间:2017-01-31 10:03:41来源:linux网站作者:时光旅行的懒猫
开始拾起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中的编码问题
python2:
python2和python3中的编码问题
可以看到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()).
 
本文永久更新地址:http://www.linuxdiyf.com/linux/28069.html