python2.x和3.x中的輸出語句有着明顯不同
2.x中的print不是個函數,輸出格式如下
1 Python 2.7.12+ (default, Aug 4 2016, 20:04:34) 2 [GCC 6.1.1 20160724] on linux2 3 Type "help", "copyright", "credits" or "license" for more information. 4 >>> print "There is only %d %s in the sky."%(1,'sun') 5 There is only 1 sun in the sky.
3.x中的print成了函數,輸出格式如下
1 Python 3.5.2+ (default, Aug 5 2016, 08:07:14) 2 [GCC 6.1.1 20160724] on linux 3 Type "help", "copyright", "credits" or "license" for more information. 4 >>> print("There is only %d %s in the sky."%(1,'sun')) 5 There is only 1 sun in the sky.
爲什麼要做出這樣的變化,主要原因有以下幾點:
1.print不是函數,不能使用help(),對使用者不方便。
python2中help(print)會報錯。
1 >>> help(print) 2 File "<stdin>", line 1 3 help(print) 4 ^ 5 SyntaxError: invalid syntax
python3中,可以使用help(print),清楚的看到print的參數。
1 Help on built-in function print in module builtins: 2 3 print(...) 4 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 5 6 Prints the values to a stream, or to sys.stdout by default. 7 Optional keyword arguments: 8 file: a file-like object (stream); defaults to the current sys.stdout. 9 sep: string inserted between values, default a space. 10 end: string appended after the last value, default a newline. 11 flush: whether to forcibly flush the stream. 12 (END)
2.從上面的help(print)中我們也可以看到在print()中的兩個重要參數,sep和end。這兩個參數使print()相比print多了兩個新功能,自定義間隔符(默認空格)和結束符(默認回車)。
1 >>> print("123","456","789") 2 123 456 789 3 >>> print("123","456","789",sep='-') 4 123-456-789
1 >>> x=1024 2 >>> print(t) 3 256 4 >>> print(t,end=" end") 5 256 end>>> 6 >>> print(t,end=" end\n") 7 256 end
3.print()重定向輸出文件更加方便。
2.x需要print>>重定向輸出,感覺代碼很混亂。
1 >>> out=open("test.txt","w") 2 >>> print>>out,"123"
3.x中輸出文件成了一個參數,使用更方便。
1 >>> out=open("test.txt","w") 2 >>> print("123",file=out)
4.python2.x中print語句的格式化輸出源自於C語言的格式化輸出,這種語法對於C這種靜態語言比較適用,但是對於擁有很多先進數據結構的python來說就有點力不從心了。python的元組,列表,字典,集合等不適合用這種結構表示,這些數據結構大多元素用下標表示,在這種結構中寫出來很混亂。python3.x的print()函數提供了有點類似C#(不知道這麼說對不對)中的格式化輸出函數format()。另外print()也兼容原來的格式化輸出方式。
1 >>> print("%s is %s."%('Aoko','good')) 2 Aoko is good.
format()讓輸出格式更清晰。
1 >>> print("{0} is {1}.".format('Aoko','good')) 2 Aoko is good.
format()支持數組下標,使python中的一些數據結構輸出更加方便。
1 >>> name=["Kaito",5] 2 >>> print("{0[0]} has {0[1]} dollars.".format(name)) 3 Kaito has 5 dollars.
format()下的格式限定符,和原來的差不多。
1 >>> x=5.6 2 >>> print("{0:4f}".format(x)) 3 5.600000
由此看來,print()相比print還是有很大進步的。說句題外話,我希望更多的python用戶多花點時間實現代碼對新版本的兼容,而不是花時間用在爭論“python2和python3誰更好”的口水戰上。python作爲一種免費語言給我們帶來了很多方便,我們不應該吝惜自己那麼一點時間。花一點時間讓python發展下去,變得更強。
出處:http://www.cnblogs.com/kaitoex/p/6085606.html