zoukankan      html  css  js  c++  java
  • 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()).

  • 相关阅读:
    [每日短篇] 1C
    项目Alpha冲刺 Day12
    项目Alpha冲刺 Day12
    [转载]MVC中单用户登录
    GitLab
    Git 版本控制
    Jenkins持续集成
    Jenkins安装
    Docker 网络基础原理
    java中内存的使用
  • 原文地址:https://www.cnblogs.com/timeship/p/4865328.html
Copyright © 2011-2022 走看看