1. 程式人生 > >Python 列印和輸出

Python 列印和輸出

簡述

在程式設計實踐中,print 的使用頻率非常高,特別是程式執行到某個時刻,要檢測產生的結果時,必須用 print 來列印輸出。

關於 print 函式,前面很多地方已經提及過,可用於寫入標準輸出。現在,是時候該深入了。

注意:這裡強調的是“print 函式”,而不是“print 語句”。

|

深入 print

在 Python 2.x 中,print 是一個語句,但是在 Python 3.x 中,它是一個函式。如果 2.x 和 3.x 都使用過,你就會發現差異有多麼大。

進入 3.x 的互動式 shell,嘗試使用“print 語句”:

[[email protected]
~]$ python Python 3.5.2 (default, Mar 29 2017, 11:05:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> print 'Python' ... SyntaxError: Missing parentheses in call to 'print'

對於大多數人來說,這個錯誤資訊再熟悉不過了。正如上面所提到的那樣,print 是 3.x 中的一個函式,與其他函式一樣,引數應該被圓括號括起來:

>>> print('Python')
Python

print 函式

要了解 print 函式的用途,可以使用 help() 來尋求幫助:

>>> 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.

將物件輸出到文字流檔案,由 sep 分開,然後以 end 結束。如果 sep、end、file 和 flush 出現,則必須以關鍵字引數的形式指定。

不使用關鍵字引數

print 函式可以列印任意數量的值(value1, value2, …),這些值由逗號分隔。

>>> age = 18
>>> 
>>> print('age', age)
age 18

很容易發現,兩個值之間有一個分隔符 - 空格(預設值),這取決於 sep。

分隔符

如果要重新定義分隔符,可以通過 sep 來指定。

>>> print('age', age, sep='')  # 去掉空格
age18
>>> 
>>> print('www', 'python', 'org', sep='.')  # 以 . 分割
www.python.org

結束符

在 print 中,字串後面會跟一個 \n(換行),前面的示例體現的不是很明顯,換一個方式就顯示出來了。

>>> for letter in 'Python':
...     print(letter)
... 
P
y
t
h
o
n

每列印一個就換行,再列印下一個,這就是 \n 所起的作用。

要改變這種行為,可以給 end 分配一個任意字串:

>>> for letter in 'Python':
...     print(letter, end='-')
... 
P-y-t-h-o-n->>> 

輸出重定向

預設情況下,print 的輸出被髮送到標準輸出流(sys.stdout)。通過重新定義 file,可以將輸出傳送到不同的流(例如:檔案或 sys.stderr)中。

>>> f = open('data.txt', 'w')
>>> print('I am a Pythonista', file=f)
>>> f.close()

可以看到,在互動式 shell 中,沒有得到任何輸出,輸出被髮送到檔案 data.txt 中:

[wang@localhost ~]$ cat data.txt 
I am a Pythonista

也可以通過這種方式將輸出重定向到標準錯誤(sys.stderr)通道:

>>> import sys
>>> 
>>> print('age: 18', file=sys.stderr)
age: 18

輸出是否緩衝通常由檔案決定,但是如果 flush 是 true,則流將被強制重新整理。