HOWTO · Python

Python 中在同一行上列印

本教程演示瞭如何在 Python 中在同一行上列印。

本頁內容

本教程將講解 Python 中在同一行列印多個東西的各種方法。通常情況下,print() 方法每次都會列印新行中的內容。我們可以使用下面的方法在 Python 中在同一行列印多個內容。

在 Python 中使用 print() 函式在同一行上進行多次列印

print 方法接收一個字串或任何有效的物件作為輸入,將其轉換為一個字串,並列印在螢幕上。要在 Python 中使用 print 函式在同一行列印多個東西,我們將不得不根據 Python 版本的不同遵循不同的方法。

Python 2.x

在 Python 2.x 中,我們可以在 print 方法的末尾加上 , 操作符,在同一行上多次列印。下面的示例程式碼演示瞭如何在 print 函式中實現這一點。

print "hello...",
print "how are you?"

輸出:

hello...how are you?

Python 3.x

而在 Python 3.x 中,我們必須改變 print() 方法的 end 引數的值,因為它預設設定為\n。下面的示例程式碼演示了我們如何使用 print() 方法,並將 end 引數設定為"",在同一行上多次列印。

print("hello...", end=""),
print("how are you?")

輸出:

hello...how are you?

在 Python 中使用 sys 模組的 stdout.write() 方法在同一行上多次列印

sys 模組的 stdout.write() 方法在螢幕上列印輸出。由於 stdout.write() 方法預設不在字串末尾新增新行,所以它可以用來在同一行上列印多次。

與 print() 方法不同的是,這個方法可以在所有的 Python 版本上使用,但是我們需要先匯入 sys 模組才能使用 stdout.write() 方法。下面的示例程式碼展示瞭如何在 Python 中使用 stdout.write() 方法在同一行列印多個字串。

import sys

sys.stdout.write("hello...")
sys.stdout.write("how are you?")

輸出:

hello...how are you?