新聞中心
區(qū)別:python2中的print是一個關鍵字,而Python3里的print是一個函數。關鍵字用法“print 要打印的內容”;函數用法“print(要打印的內容)”。
創(chuàng)新互聯專注于企業(yè)全網營銷推廣、網站重做改版、紅花崗網站定制設計、自適應品牌網站建設、H5頁面制作、成都做商城網站、集團公司官網建設、成都外貿網站建設、高端網站制作、響應式網頁設計等建站業(yè)務,價格優(yōu)惠性價比高,為紅花崗等各大城市提供網站開發(fā)制作服務。
總地來說, Python2.7的print不是一個function,而Python3里的print是一個function。
兩都調用方式的主要區(qū)別如下:
print 'this is a string' #python2.7
print('this is a string') #python3
當然,python2.7里你也可以用括號把變量括起來, 一點都不會錯:
print('this is a string') #python2.7
但是python3將print改成function不是白給的:
1. 在python3里,能使用help(print)查看它的文檔了, 而python2不行:
>>help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
2 . 在python3里,能更方便的使用輸出重定向
python2.7里,你需要以類似于C++的風格完成重定向:
with open('print.txt', 'w') as f:
print >> f, 'hello, python!'
在python3里:
with open('print.txt', 'w') as f:
print('hello, python!', file = f)
file是python3 print新加的一個參數。 另一個很handy的參數是sep, 例如打印一個整數數組, 但你想用星號而不是空格連接。python2時可能需要寫一個循環(huán)來完成, python3里這樣就行了:
a = [1, 2, 3, 4, 5] print(*a, sep = '*')
最后, 如果想在python2.7里使用python3的print,只需要在第一句代碼前加入:
from __future__ import print_function
注意, from __future__ import ...一類的語句一定要放在代碼開始處。
推薦課程:python教程之Django視頻教程
分享題目:創(chuàng)新互聯Python教程:python3與2中print有什么區(qū)別?
文章轉載:http://m.5511xx.com/article/cddddeo.html


咨詢
建站咨詢

