zoukankan      html  css  js  c++  java
  • python2 vs python3的区别汇总

    1.str的区别

    python2 中 unicode 和 str 之间的转换及与python3 str 的区别

    由此引申出加解密时的str的处理:

    # 基于python3
    import base64
    
    str01 = "blue加勒比"
    
    str_base = base64.b64encode((":"+str01).encode("utf-8")) # base64加密需要bytes类型,所以将string编码encode为bytes类型, 返回的也是bytes类型
    
    print(str_base) # type:bytes
    print(type(str_base))
    
    temp = str_base.decode("utf-8") # 如果转化为string,需要将bytes类型解码,decode,等同于 str(str_base, encoding="utf-8")
    print(temp)
    print(type(temp)) # type: str
    ------
    结果:
    b'OmJsdWXliqDli5Lmr5Q='
    <class 'bytes'>
    OmJsdWXliqDli5Lmr5Q=
    <class 'str'>
    
    ********************************************
    基于python2
    import hashlib
    import base64
    
    username = "username"
    password = hashlib.sha256(username).hexdigest() # py2的str可以认为和unicode同类型,不用转bytes类型,所以此处直接sha256加密后通过hexdigest()方法解码
    hash_str = hashlib.sha256(username + str(int(time_now)) + password).hexdigest() # 同上
    passwordHash = base64.b64encode(hash_str)[:12] # 由于py2中str 等同于unicode,base64加密时,也是不用将str转为byte类型
    

    2.python3 中的reload(sys)

    import sys
    reload(sys)
    sys.setdefaultencoding(‘utf-8’)
    
    以上是python2的写法,但是在python3中这个需要已经不存在了,这么做也不会什么实际意义。
    在Python2.x中由于str和byte之间没有明显区别,经常要依赖于defaultencoding来做转换。
    在python3中有了明确的str和byte类型区别,从一种类型转换成另一种类型要显式指定encoding。
    
    但是仍然可以使用这个方法代替
    import importlib,sys
    importlib.reload(sys)
    

    3.urllib库在python2与python3中的区别

    Urllib是python提供的一个用于操作url的模块。

    在python2中,有urllib库和urllib2库。在python3中,urllib2合并到urllib库中,我们爬取网页的时候,经常用到这个库。

    升级合并后,模块中包的位置变化的地方较多。

    以下是python2与python3中常用的关于urllib库的变化:

    1.在python2中使用import urllib2————对应的,在python3中会使用import urllib.request,urllib.error
    
    2.在python2中使用import urllib————对应的,在python3中会使用import urllib.request,urllib.error,urllib.parse
    
    3.在python2中使用import urlparse————对应的,在python3中会使用import urllib.parse
    
    4.在python2中使用urllib2.urlopen————对应的,在python3中会使用urllib.request.urlopen
    
    5.在python2中使用urllib.urlencode————对应的,在python3中会使用urllib.parse.urlencode
    
    6.在python2中使用urllib.quote————对应的,在python3中会使用urllib.request.quote
    
    7.在python2中使用cookielib.CookieJar————对应的,在python3中会使用http.CookieJar
    
    8.在python2中使用urllib2.Request————对应的,在python3中会使用urllib.request.Request
    
    以上就是urllib相关模块从python2到python3的常见一些变化。
    
  • 相关阅读:
    laravel 单元测试 phpunit 运行报错 RuntimeException: No application encryption key has been specified 解决
    pace.js 自动加载进度条插件的简单使用教程
    git push 报错 ERROR: Permission to xxx.git denied to someuser
    Laravel 框架对于分表进行统计合并查询的思路
    解决tail命令提示“tail: inotify 资源耗尽,无法使用 inotify 机制,回归为 polling 机制”
    phpredis 报错 “Function Redis::setTimeout() is deprecated” 解决方法
    laravel 5.5.39 升级到 5.5.45 出现 cookie 序列化异常问题的解决
    vue.js 实战 todo list
    BootstrapVue 安装指南
    05js语法检查、js兼容性处理
  • 原文地址:https://www.cnblogs.com/davis12/p/14823069.html
Copyright © 2011-2022 走看看