python3與2版本中print的區(qū)別有哪些-創(chuàng)新互聯(lián)

創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!

創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比天心網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式天心網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋天心地區(qū)。費用合理售后完善,10余年實體公司更值得信賴。

這篇文章主要介紹python3與2版本中print的區(qū)別有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

區(qū)別:Python2中的print是一個關(guān)鍵字,而Python3里的print是一個函數(shù)。關(guān)鍵字用法“print 要打印的內(nèi)容”;函數(shù)用法“print(要打印的內(nèi)容)”。

python3與2版本中print的區(qū)別有哪些

總地來說, Python2.7的print不是一個function,而Python3里的print是一個function。
兩都調(diào)用方式的主要區(qū)別如下:

print 'this is a string' #python2.7
print('this is a string') #python3

當(dāng)然,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++的風(fēng)格完成重定向:

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新加的一個參數(shù)。 另一個很handy的參數(shù)是sep, 例如打印一個整數(shù)數(shù)組, 但你想用星號而不是空格連接。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 ...一類的語句一定要放在代碼開始處。

以上是python3與2版本中print的區(qū)別有哪些的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道!

本文標(biāo)題:python3與2版本中print的區(qū)別有哪些-創(chuàng)新互聯(lián)
文章URL:http://muchs.cn/article38/cosspp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、手機網(wǎng)站建設(shè)、域名注冊、企業(yè)建站響應(yīng)式網(wǎng)站、動態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司