国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python2 與python3的print區(qū)別小結(jié)

2020-02-22 22:53:12
字體:
供稿:網(wǎng)友

在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里:

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 瑞昌市| 方正县| 西宁市| 环江| 宜川县| 三明市| 广元市| 鸡东县| 皋兰县| 北海市| 福建省| 平果县| 青海省| 保康县| 彭阳县| 达拉特旗| 新营市| 砀山县| 建湖县| 江源县| 沧源| 紫云| 屯留县| 湟源县| 丽水市| 清河县| 剑川县| 玉环县| 安溪县| 邹城市| 渝中区| 云林县| 大理市| 滨州市| 漯河市| 黎城县| 梁山县| 辽源市| 无为县| 山东省| 五莲县|