python2中的print语句可以不用小括号。_Python 2与Python 3的区别
越來越多的庫要放棄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 worldPython 3
print輸出
hello worldprint輸出
File "<stdin>", line 1print "hello world"^ SyntaxError: Missing parentheses in call to 'print'整數相除
在Python 2中,3/2的結果是整數,在Python 3中,結果則是浮點數
Python 2
print輸出
3 / 2 = 1 3 / 2.0 = 1.5Python 3
print輸出
3 / 2 = 1.5 3 / 2.0 = 1.5Unicode
Python 2有兩種字符串類型:str和unicode,Python 3中的字符串默認就是Unicode,Python 3中的str相當于Python 2中的unicode。
在Python 2中,如果代碼中包含非英文字符,需要在代碼文件的最開始聲明編碼,如下
# -*- coding: utf-8 -*-在Python 3中,默認的字符串就是Unicode,就省去了這個麻煩,下面的代碼在Python 3可以正常地運行
a異常處理
Python 2中捕獲異常一般用下面的語法
try或者
tryPython 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輸出
[1, 2, 3, 4, 5]Python 3
map輸出
<map object at 0x7ff5b103d2b0>list輸出
[1, 2, 3, 4, 5]filter函數在Python 2和Python 3中也是同樣的區別。
不支持has_key
Python 3中的字典不再支持has_key方法
Python 2
person輸出
person has key "age": True person has key "age": TruePython 3
person輸出
person has key "age": Trueprint輸出
Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'has_key'以上是最近整理的一些,后續會繼續更新,也歡迎大家補充。
總結
以上是生活随笔為你收集整理的python2中的print语句可以不用小括号。_Python 2与Python 3的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java set第n位_数据结构与算法—
- 下一篇: socket模拟http的登陆_利用 P