Python2和Python3常用知识的区别

疫情当前,也不能正常上班,在家很是焦虑,就想着刚点啥,正好收到组长通知,以后不用Python2.7,改用Python3了,于是就开始复习它俩区别的旅途~

其实Python提供了__future__模块,把下一个新版本的新功能,导入到当前(旧版本)中

举个简单的栗子~
Python2.7导入Python3的功能

>>>print('hello','world')
('hello','world')
#上面是没有导入future模块输出的结果,下面是导入后的结果
>>>from __future__ import print_function
>>>print('hello','world')
hello world

这样新版本的特性便可以和旧版本兼容。
还有一些其他特性库,如精确除法:
(哈哈,时间比较多就再举个简单的栗子吧^^~)

>>>3/4
0
#上面是没有导入future模块输出的结果,下面是导入后的结果
>>>from __future__ import division
>>>3/4
0.75

(嘿嘿,不止我写的两个库,还有很多库,就需要大家自己去查找了,在此就不一一列举了^^~)

是不是看了半天还没有看到他们具体区别在哪里,开始有些着急了,啊哈,这就来了,年轻人要有耐心^^~

Python2.7和Python3区别

1.print函数

Python2.7

>>> print ‘ok’
ok

Python3

>>> print(‘ok’)
ok

啦啦啦,这个大家是不是觉得是小意思呀~ 那我在这里就不总结了哈^^~

2.整数除法

Python2.7

>>> 5/2
2

Python3

>>> 5/2
2.5
>>> 5//2
2
总结:

Python2.7除法结果取整,Python3 ‘ / ’ 结果精确到小数点后,若想和Python2.7结果一样,可以使用 ‘ // ’ 便可以取整了~

扫描二维码关注公众号,回复: 10242100 查看本文章

3.编码

Python2.7

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> c = '你好'.decode('gbk')
>>> c
u'\u4f60\u597d'
>>> c = '你好'
>>> c
'\xc4\xe3\xba\xc3'
扩展:
>>> type(u"ass")
<type 'unicode'>
>>> type("ass".decode('utf8'))
<type 'unicode'>
#两者返回类型都是unicode类型

Python3

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> 哈哈 = 'hello'
>>> print(哈哈)
hello
>>> 哈哈
'china'
>>> n ='你好'
>>> n
'你好'
扩展:
>>> type(u'asd')
<class 'str'>
>>> type("asd".decode('utf8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
#报错,Python3不允许这样写,并且Python3特有的byte类型
>>> type(b'a')
<class 'bytes'>
>>> type(b'12')
<class 'bytes'>
总结:

Python2.7默认编码是ascii,文件顶部需写# coding=utf-8
Python3默认编码utf-8,所以文件顶部不需要些 # coding=utf-8

4.xrange,range

Python2.7

>>> range(5)
[0, 1, 2, 3, 4]
>>> xrange(5)
xrange(5)

Python3

>>> range(3)
range(0, 3)
>>> li = list(range(3))
>>> li
[0, 1, 2]
总结:

Python2.7 range生成list,xrange是生成器,Python3 统一用range,想输出列表,需要使用list() 哦~

5.处理异常

Python2.7

try:
	pass
except Exception, e:
	raise e

Python3

try:
	pass
except Exception as e:
	raise e
总结:

Python2.7可以不写as,Python3必须写as 呢~

6.map

Python2.7

>>> def Num(a,b):return(a,b)
...
>>> L1 = [1,2,3,4,5,6,7]
>>> L2 =  [ 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven' ]
>>> map(Num,L1,L2)
[(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven')]

Python3

>>> def Num(a,b):return(a,b)
...
>>> L1 = [1,2,3,4,5,6,7]
>>> L2 =  [ 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven' ]
>>> map(Num,L1,L2)
<map object at 0x000001F4AB1B4390>
>>> list(map(Num,L1,L2))
[(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven')]
总结:

Python2.7 返回list,Python3 若想返回list,需使用list() 哦~

7.cmp(),operator

Python2.7

>>> cmp(1.1,2)
-1
>>> cmp(3,1)
1
>>> cmp(4,4)
0

Python3

>>> import operator
>>> operator.gt(2,1)
True
>>> operator.ge(2,5)
False
>>> operator.eq(2,2)
True
>>> operator.le('2dgfh','aa')
True
>>> operator.lt('asd','fh')
True
>>> operator.ne('asd','fh')
True
总结:

Python2.7 cmp(x,y)函数,x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1;
Python3取消cmp()函数,添加了新模块operator,返回布尔值
operator.gt(x,y) #greater than(大于)
operator.ge(x,y) #greater and equal(大于等于)
operator.eq(x,y) #equals(等于)
operator.le(x,y) #less and equal(小于等于)
operator.lt(x,y) #less than (小于)
operator.ne(x,y) #not equals(不等于)

8.raw_input, input

Python2.7

>>> name = raw_input('姓名:')
姓名:哈哈
#输入中文名字
>>> name
'\xb9\xfe\xb9\xfe'
>>> type(name)
<class 'str'>

>>> name = raw_input('姓名:')
姓名:hhh
#输入字母名字
>>> name
'hhh'
>>> type(name)
<class 'str'>

>>> age = raw_input('年龄:')
年龄:12
>>> age
'12'
>>> type(age)
<class 'str'>

Python3

>>> name = input('姓名:')
姓名:哈哈
>>> name
'哈哈'
>>> type(name)
<class 'str'>

>>> name = input('姓名:')
姓名:hh
>>> name
'hh'
>>> type(name)
<class 'str'>

>>> age = input('年龄:')
年龄:13
>>> age
'13'
>>> type(age)
<class 'str'>

9.iteritems

Python2.7

>>> info = {'name':'xiaohong','age':'12','gender':'girl','score':'98'}
>>> info
{'gender': 'girl', 'age': '12', 'score': '98', 'name': 'xiaohong'}
>>> b=info.iteritems()
>>> b
<dictionary-itemiterator object at 0x000000000320C188>
>>> list(b)
[('gender', 'girl'), ('age', '12'), ('score', '98'), ('name', 'xiaohong')]
>>>
>>> info = {'姓名':'小红','年龄':'12','性别':'女','成绩':'98'}
>>> info
{'\xb3\xc9\xbc\xa8': '98', '\xc4\xea\xc1\xe4': '12', '\xd0\xd5\xc3\xfb': '\xd0\xa1\xba\xec', '\xd0\xd4\xb1\xf0': '\xc5\xae'}
>>> a = info.iteritems()
>>> a
<dictionary-itemiterator object at 0x000000000320C458>
>>> list(a)
[('\xb3\xc9\xbc\xa8', '98'), ('\xc4\xea\xc1\xe4', '12'), ('\xd0\xd5\xc3\xfb', '\xd0\xa1\xba\xec'), ('\xd0\xd4\xb1\xf0', '\xc5\xae')]

Python3

>>> info = {'姓名':'小红','年龄':'12','性别':'女','成绩':'98'}
>>> info
{'成绩': '98', '姓名': '小红', '年龄': '12', '性别': '女'}
>>> c = info.items()
>>> c
dict_items([('成绩', '98'), ('姓名', '小红'), ('年龄', '12'), ('性别', '女')])
>>> type(c)
<class 'dict_items'>
总结:

Python2.7中,iteritems()返回操作列表的迭代器
Python3 iteritems()方法废除,使用items替换,可以用for遍历 哦~

10.nonlocal

Python2.7

def function():
	num = 2
	def fun2():
		print 'fun2',num
		num = 5
		print 'fun22',num
	print 'function3',num
	fun2()
	print 'function4',num
function()

**Python3 **

def function():
	num = 2
	def fun2():
		nonlocal num
		print('fun2 nonlocal',num)
		num = 5
		print('fun2 local',num)
	print('function local',num)
	fun2()
	print('function local',num)
function()

最后一个nonlocal的我没有测试,如果你们有测试的结果然后观察一下区别,如果乐意分享一下的话,非常欢迎 ^ 0 ^~
祈祷疫情快快消失 ~~~~~~ over ~~~~~~~~~

发布了13 篇原创文章 · 获赞 16 · 访问量 1915

猜你喜欢

转载自blog.csdn.net/weixin_43614573/article/details/104559143