如何在 Python 中編寫多行字串(三引號和連接)

了解在 Python 中編寫多行字串的最佳方法。探索三引號、括號串聯、換行連接方法和格式控制。

在編輯器中嘗試此解決方案

概述

在應用程式中編寫文字區塊(例如 SQL 查詢、HTML 範本、CLI 指令或冗長的偵錯訊息)時,您通常需要將字串值跨多行。 Python 提供了多種定義多行字串的方法,每種方法都有不同的格式意義。

編寫多行字串最直接、最常見的方法是使用三引號語法(`'''` 或 `"""`)。三引號字串按字面保留所有字元輸入,包括原始換行符和縮排。這使得格式化高度可視化,但有一個缺點:用於對齊循環或類別內的程式碼的任何前導表符或空格都將成為實際字串值的一部分。

要定義在視覺上跨越原始程式碼中的多行但編譯為單一長行(或不捕獲程式碼縮排空格)的多行字串,您可以將標準單引號字串括在括號中。 Python 會自動將括號內相鄰的字串文字連接起來,使您的程式碼乾淨且具有高度可讀性。

程式碼和執行輸出

此腳本示範如何使用三引號、括號字串連接和簡潔縮排來編寫多行文字。

multiline_strings.py
在編輯器中嘗試
# 1. Triple Quote Syntax (preserves all newlines and indentation)
sql_query = """SELECT id, username, email
FROM users
WHERE active = True
ORDER BY id DESC;"""

print("--- Triple Quotes Query ---")
print(sql_query)

# 2. Parentheses Concatenation (splits code line, compiles into single line)
long_message = (
    "This is a long message that we split "
    "across multiple lines in our editor, "
    "but it compiles into a single text block."
)
print("\n--- Parentheses Concatenation ---")
print(long_message)

# 3. Joining list elements for clean line breaks
lines = [
    "First instruction line.",
    "Second instruction line.",
    "Third instruction line."
]
joined_text = "\n".join(lines)
print("\n--- Joined Lines ---")
print(joined_text)
端子輸出
--- Triple Quotes Query ---
SELECT id, username, email
FROM users
WHERE active = True
ORDER BY id DESC;

--- Parentheses Concatenation ---
This is a long message that we split across multiple lines in our editor, but it compiles into a single text block.

--- Joined Lines ---
First instruction line.
Second instruction line.
Third instruction line.

逐步實施

  • 使用三引號(''' 或 """)編寫保留文字換行符的長文字區塊。
  • 將連續的字串括在不帶逗號的括號 ( ) 中,以直觀地分割程式碼,而不在輸出中添加換行符。
  • 在類別或函數內使用三引號來清理前導縮排時,請使用 textwrap.dedent() 。

常見問題解答

如何從嵌套的三引號字串中刪除前導縮排?

導入內建的 textwrap 模組並將字串傳遞給 textwrap.dedent(text) 以清理前導空格。

單三引號和雙三引號有什麼差別?

''' 和 """ 之間沒有功能差異。選擇約定並在整個專案中始終堅持它。

相關主題

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。