python2和python3里的print有什么區(qū)別?很多人都不太了解,今天小編為了讓大家更加了解print,所以給大家總結(jié)了以下內(nèi)容,一起往下看吧。
成都創(chuàng)新互聯(lián)主營嘉興網(wǎng)站建設的網(wǎng)絡公司,主營網(wǎng)站建設方案,成都app軟件開發(fā),嘉興h5微信小程序開發(fā)搭建,嘉興網(wǎng)站營銷推廣歡迎嘉興等地區(qū)企業(yè)咨詢
在Python2和Python3中都提供print()方法來打印信息,但兩個版本間的print稍微有差異
主要體現(xiàn)在以下幾個方面:
1.python3中print是一個內(nèi)置函數(shù),有多個參數(shù),而python2中print是一個語法結(jié)構(gòu);
2.Python2打印時可以不加括號:print 'hello world', Python3則需要加括號 print("hello world")
3.Python2中,input要求輸入的字符串必須要加引號,為了避免讀取非字符串類型發(fā)生的一些行為,不得不使用raw_input()代替input()
1. python3中,或許開發(fā)者覺得print同時具有兩重身份有些不爽,就只留了其中函數(shù)的身份:
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
從上面的方法原型可以看出,
①. print可以支持多個參數(shù),支持同時打印多個字符串(其中...表示任意多個字符串);
②. sep表示多個字符串之間使用什么字符連接;
③. end表示字符串結(jié)尾添加什么字符,指點該參數(shù)就可以輕松設置打印不換行,Python2.x下的print語句在輸出字符串之后會默認換行,如果不希望換行,只要在語句最后加一個“,”即可。但是在Python 3.x下,print()變成內(nèi)置函數(shù),加“,”的老方法就行不通了。
>>> print("python", "tab", ".com", sep='') pythontab.com >>> print("python", "tab", ".com", sep='', end='') #就可以實現(xiàn)打印出來不換行 pythontab.com
當然,python2.7里你也可以用括號把變量括起來, 一點都不會錯:
print('this is a string') #python2.7
但是python3將print改成function不是白給的:
在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.
在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新加的一個參數(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 ...一類的語句一定要放在代碼開始處。
以上就是python2和python3里的print有什么區(qū)別的詳細內(nèi)容了,看完之后是否有所收獲呢?如果想了解更多相關內(nèi)容,歡迎來創(chuàng)新互聯(lián)行業(yè)資訊!