亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2018年01月16日 21:48:53   投稿:mdxy-dxy  
這篇文章主要介紹了python2 與python3的print區(qū)別小結(jié),需要的朋友可以參考下

在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í)可以不加括號:print 'hello world', Python3則需要加括號 print("hello world")

3.Python2中,input要求輸入的字符串必須要加引號,為了避免讀取非字符串類型發(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í)可以不加括號:print 'hello world', Python3則需要加括號 print("hello world")

python3中print必須使用括號,因?yàn)樗褪且粋€(gè)函數(shù)。

總地來說, 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里你也可以用括號把變量括起來, 一點(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ù)組, 但你想用星號而不是空格連接。python2時(shí)可能需要寫一個(gè)循環(huán)來完成, python3里這樣就行了:

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

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

from __future__ import print_function

注意, from __future__ import ...一類的語句一定要放在代碼開始處。

print輸出差異:同一段代碼

#/usr/bin/env python
#coding:utf-8
for i in range(1,10):
    for j in range(1,10):
        for k in range(1,10):
            if(i != k)and(i != j)and(k != j):
                print(i,j,k)

pyhon2的輸出為 i,j,k
python3的輸出為 i j k
python3的輸出直接屏蔽了逗號。

另python2 的print后序可不添加括號。
phthon3必須添加括號。

相關(guān)文章

最新評論