Python 三引號


Python 的三引號允許字串跨越多行,包括逐字 NEWLINE、TAB 和任何其他特殊字元,因而可以派上用場。

三引號的語法包括三個連續的單引號或雙引號。

示例

 線上演示

#!/usr/bin/python
para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up.
"""
print para_str

輸出

執行上述程式碼時,將產生以下結果。

請注意,每個特殊字元如何轉換為其列印形式,一直到 "up。"結尾和關閉的三引號之間的字串末尾的最後一個 NEWLINE。另外請注意,NEWLINE 可能會出現在行尾的顯式回車或其轉義碼 (\n) 中 −

this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up.

原始字串根本不將反斜槓視為特殊字元。輸入原始字串的每個字元都將保持原樣 −

示例

 線上演示

#!/usr/bin/python
print 'C:\nowhere'

輸出

執行上述程式碼時,將產生以下結果 −

C:\nowhere

現在,讓我們使用原始字串。我們將表示式置於 r'expression' 中,如下所示 −

示例

 線上演示

#!/usr/bin/python
print r'C:\nowhere'

輸出

執行上述程式碼時,將產生以下結果 −

C:\nowhere

更新於:2020 年 1 月 28 日

6K+ 瀏覽次數

開啟您的職業生涯

完成課程並獲得認證

開始學習
廣告