python2.x 與python3.x 的區別
所有的區別都來源於python官方文檔,建議朝python3.x版本轉換的童鞋都看下官方文檔https://docs.python.org/3/whatsnew/index.html
Print Is A Function
主要差別
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x,
New: print(x, end=" ")
Old: print
New: print()
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y)
New: print((x, y))
python3 不在自動支持空白空格
The print() function doesn’t support the “softspace” feature of the old print statement. For example, in Python 2.x, print "A\n", "B" would write "A\nB\n"; but in Python 3.0, print("A\n", "B") writes "A\n B\n".
排序比較
1.python3不在支持不同類型間的<, <=, >=, >操作,會拋出一個TypeError.None < None也是如此
2.sotred和list.sort()不在接受cmp函數,
3.刪除了cmp函數,刪除__cmp__。如果實現排序需要使用__lt__ __hash__ __eq__.如果確實需要使用類似cmp(a,b)的功能。使用如下表達式(a>b)-(a<b)
整型
1.python3不在存在long
2.1/2 返回float,如果實現取證使用1//2
3.長整型repr()不在表現爲"11L"
4.Octal literals are no longer of the form 0720; use 0o720 instead.
文本
八進制表示方式。
1.八進制限制使用0o720替代0720
nonlocal關鍵字
新的解包規則
(a, *b, c) = range(5)
print(a)
0
print(b)
[1, 2, 3]
print(c)
4
異常新的語法
try:
pass
except Exception as exe:
pass
元類使用
1.新的語法
class C(metaclass=M):
pass
2. 模塊的__metaclass__語法不在支持