大爽Python入門教程 4-4 深入了解`print`


大爽Python入門公開課教案 點擊查看教程總目錄

print為例,認識函數。
學習讀懂函數的過程。

1 內置函數

現在,讓我們再來詳細認識下print這個函數。
print屬於內置函數,built-in functions

內置函數的官方文檔為 Built-in Functions

如下圖所示

在其中,點擊print函數鏈接,跳轉到print對應的說明。
截圖如下

2 試讀print官方文檔

先嘗試讀下官方文檔。
這里我們一句一句來讀。
首先是函數聲明,

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

先初步解讀下這些形參

  • *objects: 接受不定數量的參數。
  • sep=' ': sep默認值為' '
  • end='\n': end默認值為'\n'
  • file=sys.stdout: sep默認值為sys.stdout
  • flush=False: flush默認值為False

然后繼續往下

Print objects to the text stream file, separated by sep and followed by end.
sep, end, file and flush, if present, must be given as keyword arguments.

objects打印到文本流file中,使用sep來分割,最后接end
如果存在sependfileflush, 必須使用關鍵字參數來傳參。

All non-keyword arguments are converted to strings like str()`` does and written to the stream, separated by sepand followed byend. Both sepandendmust be strings; they can also beNone, which means to use the default values. If no objectsare given,print()will just writeend`.

所有非關鍵字參數(即位置參數),都會使用str()方法轉換為字符串並寫入流,使用sep來分割,最后接end
sepend都必須是字符串;它們也可以是None,這意味着使用默認值。
如果沒有傳入objectsprint() 將只輸出end

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.
Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects.
For these, use file.write(...) instead.

file參數必須是具有 write(string)方法的對象; 如果它不存在或無,將使用 sys.stdout
由於打印的參數被轉換為文本字符串,print()不能用於二進制模式文件對象。
對於這些,請改用file.write(...)

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

輸出是否緩沖通常由file決定,但如果flush關鍵字參數為真,則流被強制刷新。

Changed in version 3.3: Added the flush keyword argument.

在 3.3 版更改: 添加了 flush 關鍵字參數。

說實話,我也沒太讀懂flush
file也只是大概懂了。。。

3 大概總結

再回來看下函數頭print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
fileflush太高級了,就不去理解了。
說下這三個

  • *objects: 接受所有的位置參數(非關鍵詞參數),輸出這些
  • sep: 輸出時,用sep作為分隔符,不指定則使用空格
  • end: 輸出時,用end來結尾,不指定則使用換行\n

4 代碼示例

print("a", end=" ")
print("b", end=" ")
print("c", end=" ")
print()
print("-"*20)
print(1, 2, 3, 4, sep="-")
print("-"*20)
words = list("abcdefg")

for word in words:
    print(word, end=",")

輸出如下

a b c 
--------------------
1-2-3-4
--------------------
a,b,c,d,e,f,g,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM