首頁  >  文章  >  後端開發  >  以下是一些適合本文的問題式標題: * Python 列印時如何控制換行符和空格? * 想要從 Python 列印輸出中刪除換行符或空格嗎?這裡的

以下是一些適合本文的問題式標題: * Python 列印時如何控制換行符和空格? * 想要從 Python 列印輸出中刪除換行符或空格嗎?這裡的

Linda Hamilton
Linda Hamilton原創
2024-10-28 15:05:01393瀏覽

Here are a few question-style titles that fit the article:

* How Can I Control Newlines and Spaces When Printing in Python?
* Want to Remove Newlines or Spaces from Your Python Print Output? Here's How!
* Python Printing: Mastering the `end` and `sep` P

在 Python 中控制列印輸出

在 Python 中列印字串時,經常會在列印文字末尾遇到換行符或空格。在某些情況下,這可能是不可取的,尤其是需要精確的輸出格式時。

抑制換行符

要省略自動附加到列印字串的換行符,請在 print 函數中使用 end 參數。透過將 end 設為空字串 (''),可以防止 Python 在列印後添加換行符。

<code class="python">print('h', end='')  # prints 'h' without a newline</code>

抑制空格

如果連續列印多個字串並且如果希望阻止 Python 在它們之間插入空格,可以在 print 函數中使用 sep 參數。將 sep 設為空字串將省略預設的空格分隔符。

<code class="python">print('a', 'b', 'c', sep='')  # prints 'abc' without any whitespace between the characters</code>

真實範例

考慮以下程式碼:

<code class="python">for i in range(3):
    print('h')</code>

此程式碼執行print 語句三次,輸出結果:

h
h
h

如果我們希望打印不帶換行符的字符,我們可以使用end 參數:

<code class="python">for i in range(3):
    print('h', end='')</code>

這將產生輸出:

hhh

同樣,如果我們希望打印沒有空格和換行符的字符,我們可以使用sep 和end 參數:

<code class="python">for i in range(3):
    print('h', end='', sep='')</code>

這將產生輸出:

h

以上是以下是一些適合本文的問題式標題: * Python 列印時如何控制換行符和空格? * 想要從 Python 列印輸出中刪除換行符或空格嗎?這裡的的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn