在Python2和Python3中都提供print()方法來打印信息,但兩個(gè)版本間的print稍微有差異
主要體現(xiàn)在以下幾個(gè)方面:
1.python3中print是一個(gè)內(nèi)置函數(shù),有多個(gè)參數(shù),而python2中print是一個(gè)語法結(jié)構(gòu);
2.Python2打印時(shí)可以不加括號(hào):print 'hello world', Python3則需要加括號(hào) print("hello world")
3.Python2中,input要求輸入的字符串必須要加引號(hào),為了避免讀取非字符串類型發(fā)生的一些行為,不得不使用raw_input()代替input()
1. python3中,或許開發(fā)者覺得print同時(shí)具有兩重身份有些不爽,就只留了其中函數(shù)的身份:
print(value1, ..., sep=' ', end='/n', file=sys.stdout, flush=False)
從上面的方法原型可以看出,
①. print可以支持多個(gè)參數(shù),支持同時(shí)打印多個(gè)字符串(其中...表示任意多個(gè)字符串);
②. sep表示多個(gè)字符串之間使用什么字符連接;
③. end表示字符串結(jié)尾添加什么字符,指點(diǎn)該參數(shù)就可以輕松設(shè)置打印不換行,Python2.x下的print語句在輸出字符串之后會(huì)默認(rèn)換行,如果不希望換行,只要在語句最后加一個(gè)“,”即可。但是在Python 3.x下,print()變成內(nèi)置函數(shù),加“,”的老方法就行不通了。
>>> print("python", "tab", ".com", sep='') pythontab.com >>> print("python", "tab", ".com", sep='', end='') #就可以實(shí)現(xiàn)打印出來不換行 pythontab.com Python2打印時(shí)可以不加括號(hào):print 'hello world', Python3則需要加括號(hào) print("hello world")
python3中print必須使用括號(hào),因?yàn)樗褪且粋€(gè)函數(shù)。
總地來說, Python2.7的print不是一個(gè)function,而Python3里的print是一個(gè)function。
兩都調(diào)用方式的主要區(qū)別如下:
print 'this is a string' #python2.7print('this is a string') #python3當(dāng)然,python2.7里你也可以用括號(hào)把變量括起來, 一點(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里:
新聞熱點(diǎn)
疑難解答
圖片精選