首頁  >  文章  >  後端開發  >  python續行符號是什麼

python續行符號是什麼

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-06-20 16:30:0550049瀏覽

跨行的字面字串可用以下幾種方法表示。使用續行符,即在每行最後一個字元後使用反斜線來說明下一行是上一行邏輯上的延續。

以下使用\n 來新增一行:

python續行符號是什麼

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n 意味着新行
>>> s  # 不使用 print(), \n 包含在输出中
'First line.\nSecond line.'
>>> print(s)  # 使用 print(), \n 输出一个新行
First line.
Second line.

  以下使用反斜線(\) 來續行:

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
 significant."
 
print(hello)

相關推薦:《Python影片教學

注意,其中的換行符號仍然要使用\n 表示-反斜線後的換行符號被丟棄了。以上範例將如下輸出:

This is a rather long string containing
several lines of text just as you would do in C.
    Note that whitespace at the beginning of the line is significant.

或者,字串可以被""" (三個雙引號)或''' (三個單引號)括起來。使用三引號時,換行符號不需要轉義,它們會包含在字串中。以下的例子使用了一個轉義符,避免在最開始產生一個不需要的空行。

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

其輸出如下:

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

  如果我們使用"原始"字串,那麼\n 不會被轉換成換行,行末的的反斜杠,以及原始碼中的換行符,都將作為資料包含在字串內。例如: 

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)

將會輸出:  

This is a rather long string containing\n\
several lines of text much as you would do in C.

以上是python續行符號是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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