1. 引言
在Python語言的學習過程中,
print
函數可能是我們大多數人學習會的第一個函數。但是該函數有一些特殊的用法,本文重點介紹使用該函數的八重境界。
閑話少說,我們直接開始吧!
2. Level1 基礎用法
函數
print
最最基礎的用法就是按照我們的要求,列印相應的内容。如下所示:
print("hello")
# hello
上述代碼,傳入一串字元串,運作後在終端輸出顯示。
3. Level2 列印多個參數
如果我們向
print
函數傳遞多個參數,那麼在運作時,該函數會在列印的參數之間自動插入空白字元。
如下所示:
print("apple", "orange", "pear")
# apple orange pear
4. Level3 使用end參數
實質上,函數
print
的預設參數有結束符
end
,主要用于分割列印内容。舉例如下:
print("apple", end=" ")
print("orange", end=" ")
print("pear", end=" ")
# apple orange pear
預設情況下,函數
print
中參數
end
的預設值為
\n
。如果我們傳入其他值,那麼
print
函數将會使用參數
end
的字元添加到列印内容的末尾。
舉例如下:
print("apple", end=";")
print("orange", end="!!")
print("pear", end="end")
# apple;orange!!pearend
5. Level4 使用sep參數
一般來說,函數
print
中的參數
sep
分割符,預設值為空格字元
" "
, 參數
sep
主要用于添加到print函數的多個參數之間。
舉例如下:
print(1, 2, 3) # 1 2 3 # default sep is " "
print(1, 2, 3, sep=";") # 1;2;3
print(1, 2, 3, sep="#") # 1#2#3
print(1, 2, 3, sep="4") # 14243
6. Level5 使用pprint
如果我們有一個具有多層嵌套的複雜資料結構,此時我們可以使用
pprint
來列印它,而不是編寫一個for循環來可視化它。
舉例如下:
from pprint import pprint
data = [
[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
[[4, 5, 6], [4, 5, 6], [4, 5, 6]],
[[7, 8, 9], [7, 8, 9], [7, 8, 9]]
]
pprint(data)
輸出如下:

7. Level6 彩色輸出
想要在Python中列印彩色輸出,我們一般使用第三方庫
colorama
。這意味着我們首先需要使用pip安裝它。
在終端中運作
pip install colorama
就可以友善地來安裝它啦。
樣例如下:
from colorama import Fore
print(Fore.RED + "hello world")
print(Fore.BLUE + "hello world")
print(Fore.GREEN + "hello world")
輸出如下:
8. Level7 輸出到檔案中
預設情況下,函數
print
的參數
file
的預設值為
sys.stdout
。這意味着我們可以使用
print
函數列印的任何内容都會在終端顯示。
當然,我們也可以改變改參數的值,将相應的列印内容輸出到檔案中,舉例如下:
print("hello", file=open("out.txt", "w"))
9. Level8 輸出重定向到檔案中
假設我們運作了一個普通的Python腳本
run.py
,輸出列印一些東西:
print("hello world")
print("apple")
print("orange")
print("pear")
接着,我們可以改變運作Python腳本的方式,使其輸出重定向到檔案中,如下:
python run.py > out.txt