Python 2 与Python 3的区别

来源:互联网 发布:逃不开的经济周期2淘宝 编辑:程序博客网 时间:2024/05/17 01:11

1. 除号/与整除号//

Python 2中,/ 是整除; 

Python 3中,/是常规除法,//是整除

2.raw_input与input

Python 2用raw_input();Python 3用input()。都表示输入函数。

3.print与print(),以及逗号

Python 2中,print “my”, print "name."可用,中间逗号会默认加一个空格,打印:my name.

Python 3中,print("my", end = " ")   print("name.", end = " ") 打印:my name.

4.range()返回值

Python 2中print range(5), 返回一个列表[0, 1, 2, 3, 4].

Python 3中print(range(5)), 返回一个对象。range(0, 5).

5.去除反引号``

Python 2中,str、repr和反引号是将python值转换为字符串的三种方法。

Python 3中去除``,全部改用repr() 。

函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为字符串的规范表示,供解释器读取的形式。

6.全局函数unicode()#

Python 2有两个全局函数可以把对象强制转换成字符串:unicode()把对象转换成Unicode字符串,还有str()把对象转换为非Unicode字符串。

Python 3只有一种字符串类型,Unicode字符串,所以str()函数即可完成所有的功能。(unicode()函数在Python 3里不再存在了。)

7.库的变化

python 3.x urllib库 urilib2库合并urllib库

urllib2.urlopen() 变urllib.request.urlopen()

urllib2.Request()变urllib.request.Request() 

urllib.quote(text)变urllib.parse.quote(text)

file()变open()

urllib.urlencode 变 urllib.parse.urlencode 

urllib2 变 urllib.reques

urlparse 变 urllib.parse

StandardError 变 BaseException

cookielib 变 http.cookiejar 

cStringIO 变 io

8.其他
dict.iteritems() 变为dict.items()

basestring超类去掉了,替换成str

except urllib2.HTTPError e: 变为except urllib2.HTTPError as e:

0 0
原创粉丝点击