溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2020-07-15 11:05:10 來(lái)源:億速云 閱讀:390 作者:清晨 欄目:編程語(yǔ)言

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

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

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

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

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

當(dāng)然,python2.7里你也可以用括號(hào)把變量括起來(lái), 一點(diǎn)都不會(huì)錯(cuò):

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新加的一個(gè)參數(shù)。 另一個(gè)很handy的參數(shù)是sep, 例如打印一個(gè)整數(shù)數(shù)組, 但你想用星號(hào)而不是空格連接。python2時(shí)可能需要寫一個(gè)循環(huán)來(lái)完成, python3里這樣就行了:

a = [1, 2, 3, 4, 5]
print(*a, sep = '*')

最后, 如果想在python2.7里使用python3的print,只需要在第一句代碼前加入:

from __future__ import print_function

注意, from __future__ import ...一類的語(yǔ)句一定要放在代碼開(kāi)始處。

以上是python3與2版本中print的區(qū)別有哪些的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI