Python 2与Python 3的区别

浏览: 1810

作者:强哥,现供职于一家大型全球电子商务网站,多年Python程序员,热爱数据,热爱AI,希望能与更多同业人交流。

个人公众号:Python与数据分析

越来越多的库要放弃Python 2了,强哥也开始转向Python 3了。最近的项目开始用Python3写了,也体会了一下2和3的区别。主要的一些区别在以下几个方面:

  • print函数

  • 整数相除

  • Unicode

  • 异常处理

  • xrange

  • map函数

  • 不支持has_key

print函数

Python 2中print是语句(statement),Python 3中print则变成了函数。在Python 3中调用print需要加上括号,不加括号会报SyntaxError

Python 2

print "hello world"

输出

hello world

Python 3

print("hello world")

输出

hello world

print "hello world"

输出

File "<stdin>", line 1
   print "hello world"
                     ^
SyntaxError: Missing parentheses in call to 'print'

整数相除

在Python 2中,3/2的结果是整数,在Python 3中,结果则是浮点数

Python 2

print '3 / 2 =', 3 / 2
print '3 / 2.0 =', 3 / 2.0

输出

3 / 2 = 1
3 / 2.0 = 1.5

Python 3

print('3 / 2 =', 3 / 2)
print('3 / 2.0 =', 3 / 2.0)

输出

3 / 2 = 1.5
3 / 2.0 = 1.5

Unicode

Python 2有两种字符串类型:str和unicode,Python 3中的字符串默认就是Unicode,Python 3中的str相当于Python 2中的unicode。

在Python 2中,如果代码中包含非英文字符,需要在代码文件的最开始声明编码,如下

# -*- coding: utf-8 -*-

在Python 3中,默认的字符串就是Unicode,就省去了这个麻烦,下面的代码在Python 3可以正常地运行

a = "你好"
print(a)

异常处理

Python 2中捕获异常一般用下面的语法

try:
   1/0
except ZeroDivisionError, e:
   print str(e)

或者

try:
   1/0
except ZeroDivisionError as e:
   print str(e)

Python 3中不再支持前一种语法,必须使用as关键字。

xrange

Python 2中有 range 和 xrange 两个方法。其区别在于,range返回一个list,在被调用的时候即返回整个序列;xrange返回一个iterator,在每次循环中生成序列的下一个数字。Python 3中不再支持 xrange 方法,Python 3中的 range 方法就相当于 Python 2中的 xrange 方法。

map函数

在Python 2中,map函数返回list,而在Python 3中,map函数返回iterator。

Python 2

map(lambda x: x+1, range(5))

输出

[1, 2, 3, 4, 5]

Python 3

map(lambda x: x+1, range(5))

输出

<map object at 0x7ff5b103d2b0>

list(map(lambda x: x+1, range(5)))

输出

[1, 2, 3, 4, 5]

filter函数在Python 2和Python 3中也是同样的区别。

不支持has_key

Python 3中的字典不再支持has_key方法

Python 2

person = {"age": 30, "name": "Xiao Wang"}
print "person has key \"age\": ", person.has_key("age")
print "person has key \"age\": ", "age" in person

输出

person has key "age":  True
person has key "age":  True

Python 3

person = {"age": 30, "name": "Xiao Wang"}
print("person has key \"age\": ", "age" in person)

输出

person has key "age":  True

print("person has key \"age\": ", person.has_key("age"))

输出

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'has_key'



Python爱好者社区历史文章大合集

Python爱好者社区历史文章列表(每周append更新一次)

福利:文末扫码立刻关注公众号,“Python爱好者社区”,开始学习Python课程:

关注后在公众号内回复课程即可获取

小编的Python入门视频课程!!!

崔老师爬虫实战案例免费学习视频。

丘老师数据科学入门指导免费学习视频。

陈老师数据分析报告制作免费学习视频。

玩转大数据分析!Spark2.X+Python 精华实战课程免费学习视频。

丘老师Python网络爬虫实战免费学习视频。

image.png

推荐 0
本文由 Python爱好者社区 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册