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

Linda Hamilton
發布: 2024-10-28 15:05:01
原創
392 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!