python2.x和python3.x的一些区别

1 使用 __future__的模块

python3.x 引入了一些与python2.x不兼容的关键字和特性。2.x中可以通过__future__模块导入新的内容

2 print函数

2.x中print是个语句,3.x中print是个方法,也是说2.x中print 或者print() 、print () 都是可以的,

print "magedu.com"
print("magedu.com")
print ("magedu.com")

不过3.x中print一定要方法的形式调用

print("magedu.com")

3 整数除法

python2.x

>>> 1/2
0

python3.x

>>> 1/2
0.5
>>> 1/0

4 Unicode

  • python2.x:ASCII的str类型,有unicode() 转成unicode类型
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
  • python3.x:Unicode(utf-8)类型str,bytes,bytearrays
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> 

5 xrange

  • python2.x xrange
  • python3.x range,使用xrange会有异常

6 异常

  • python2.x 支持两种格式

Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     a = raw_input("输入一个数:")
...     if not a.isdigit():
...         raise ValueError("a 必须是数字")
... except ValueError as e:
...     print("引发异常:",e)
... 
输入一个数:a
('\xe5\xbc\x95\xe5\x8f\x91\xe5\xbc\x82\xe5\xb8\xb8\xef\xbc\x9a', ValueError('a \xe5\xbf\x85\xe9\xa1\xbb\xe6\x98\xaf\xe6\x95\xb0\xe5\xad\x97',))

>>> try:
...     a = raw_input("输入一个数:")
...     if not a.isdigit():
...         raise ValueError("a 必须是数字")
... except ValueError,e:
...     print("引发异常:",e)
... 
输入一个数:a
('\xe5\xbc\x95\xe5\x8f\x91\xe5\xbc\x82\xe5\xb8\xb8\xef\xbc\x9a', ValueError('a \xe5\xbf\x85\xe9\xa1\xbb\xe6\x98\xaf\xe6\x95\xb0\xe5\xad\x97',))


  • python3.x 只支持as e的这种
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     a = input("输入一个数:")
...     if not a.isdigit():
...         raise ValueError("a 必须是数字")
... except ValueError as e:
...     print("引发异常:",e)
... 
输入一个数:a
引发异常: a 必须是数字
>>> 

7 next方法

  • python2.x next() 或者.next()
  • python3.x next()
__next__

8 input方法

  • python2.x raw_input()
  • python3.x input()

9 iter和list

  • python2.x 有些迭代对象直接转成list了:dict.key(),dict.values(), map, reduce,filter等等
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = map(lambda x:int(x), [x for x in "123456789"])
>>> type(lst)
<type 'list'>
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> dt = {x:x for x in range(10)}
>>> dt.values()
dict_values([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.items()
dict_items([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)])
>>> 

  • python3.x 默认返回的是可迭代对象:dict.key(),dict.values(), map, reduce,filter等等
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = map(lambda x:int(x), [x for x in "123456789"])
>>> type(lst)
<class 'map'>
>>> lst
<map object at 0x10457a128>
>>> 
>>> dt = {x:x for x in range(10)}
>>> dt.values()
dict_values([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.items()
dict_items([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)])
>>> 


10 字典

  • python2.x 字典插入无序
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> dt = {}
>>> dt["a"] = "A"
>>> dt["b"] = "B"
>>> dt["c"] = "C"
>>> dt
{'a': 'A', 'c': 'C', 'b': 'B'}
>>> 
  • python3.5以后,字典插入有序
>>> dt = {}
>>> dt["a"] = "A"
>>> dt["b"] = "B"
>>> dt["c"] = "C"
>>> dt
{'a': 'A', 'b': 'B', 'c': 'C'}
>>> 

11 字符串格式化

  • python2.x %
>>> a = "%d+%d=%d" %(1,2,3)
>>> a
'1+2=3'
  • python3.x format 和f
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "{}+{}={}".format(1,2,3)
>>> a
'1+2=3'
>>> a = 1
>>> b = 2 
>>> c = 3
>>> d = f"{a}+{b}={c}"
>>> d
'1+2=3'


12 True和False

  • python2.x True 可以被赋值
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True + True
2
>>> True = 0
>>> True + True
0
>>> 
  • python3.x True是关键字
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True+True
2
>>> True = 0
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
>>> 

python2.x 里面 while 1 要比while True 速度快一些(来自你像从前一样的Python学习笔记-python天坑系列)

➜  Desktop cat python2.py 
#! /usr/bin/python
# -*- coding: utf-8 -*-
 
import timeit
 
def while_one():
    i = 0
    while 1:
        i += 1
        if i == 10000000:
            break
 
def while_true():
    i = 0
    while True:
        i += 1
        if i == 10000000:
            break
 
if __name__ == "__main__":
    w1 = timeit.timeit(while_one, "from __main__ import while_one", number=3)
    wt = timeit.timeit(while_true, "from __main__ import while_true", number=3)
    print "while one: %s\nwhile_true: %s" % (w1, wt)
➜  Desktop python python2.py
while one: 0.646219015121
while_true: 1.01446509361

欢迎小伙伴来补充

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值