python2和python3的不同

1.print

python2:   print 'hello world' (特殊语句)

python3:   print('hello world')  (函数)

2.input

python2:  raw_input()    接收的是字符串类型,input()会根据输入的类型自行推导

python3: input()      无论输入的是什么类型,接收到的都是字符串类型

3.除法/

python2:   / 得到的就是整型类型数据

python3:/ 得到的都是浮点数类型,// 才能整除等到整型数据类型

4.类的区别

python2:python2中默认类是旧式类,需要显式继承新式类(object)来创建新式类。

                 即类在继承中,括号里写不写object继承顺序是有区别的

python3:  python3中完全移除旧式类,所有类都是新式类,但仍可显式继承object类。

                 括号里写不写object都是继承新式类,继承顺序先横向继承再纵向继承

5.捕捉异常的区别(写法,python3向下兼容):

python2: raise ValueError,'Invalid value'      except ValueError,e:

python3:    raise ValueError('Invalid value')    except ValueError as e

6.爬虫中urllib和urllib2的区别

python2中的urllib、urllib2和urlparse合并为python3中的urllib

即:python2:urllib2 -- > python3: urllib.request      

        python2:   urllib -- > python3: urllib.parse

7.编码类型的区别

Python2默认解释器编码格式是ASCII,Python3默认编码格式是UTF-8

python2改变默认解释器编码格式(将python2编码格式改成python3编码格式,避免乱码)

1> import sys

2> reload(sys)

3>sys.setdefaultencoding("utf-8")

python2: unicode字符串类型: ACSII(unicode)
                                  非unicode字符串类型: str

python3:    unicode字符串类型:str(unicode)
                                           非unicode字符串类型: bytes

这里需要注意str类型的数据在python2(decode)和python3(encode)中是不同的

字符串主要分两种: Unicode字符串、非Unicode字符串
不管何种操作系统何种编程语言 的何种编码字符串,都可以和 Unicode 互相转换。

即:Unicode字符串类型执行encode操作

       非Unicode字符串执行decode操作

8.写入文件中的不同

Python3: open()方法的写入模式
        1. 如果 write()参数是 Unicode字符串,模式必须是 w(str)
        2. 如果 write()参数是 非Unicode字符串,模式必须是 wb(二进制)

Python2: open() 方法的写入模式
        1. 如果 write()参数是 字符串(Unicode字符串、gbk、utf-8),模式一般用 w
        2. 如果 write()参数是 非字符串(图片、音视频二进制数据), 模式一般用 wb

 Python3:

        unicode_str = u"你好"
        utf8_str  = unicode.encode("utf-8")

        import sys
        sys.getdefaultencoding()   # utf-8

        # 默认写入文件为utf-8 w
        with open("test.txt", "w") as f:
            f.write(unicode_str)

        # 指定写入文件为utf-8 w
        with open("test.txt", "w", encoding="utf-8") as f:
            f.write(unicode_str)

        # 对字符串编码后再写入 wb
        with open("test.txt", "wb") as f:
            f.write(utf8_str)
            f.write(unicode_str.encode("utf-8"))


    Python2:

        unicode_str = u"你好" (unicode 编码)
        utf8_str  = unicode.encode("utf-8") (utf-8编码)

        # 对字符串编码后再写入 wb
        with open("test.txt", "wb") as f:
            f.write(utf8_str)
            f.write(unicode_str.encode("utf-8"))

        Python2的 open() 方法没有 encoding 参数,但是可以通过codecs 模式写入一个Unicode字符串,并按照指定编码保存

        import codecs
        with codecs.open("test.txt", "w", encoding="gbk") as f:
            f.write(unicode_str)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值