簡體   English   中英

在多行中連接python中的字符串

[英]Concatenate strings in python in multiline

我有一些字符串要連接,結果字符串會很長。 我還有一些要連接的變量。

如何組合字符串和變量,以便結果是多行字符串?

以下代碼拋出錯誤。

str = "This is a line" +
       str1 +
       "This is line 2" +
       str2 +
       "This is line 3" ;

我也試過這個

str = "This is a line" \
      str1 \
      "This is line 2" \
      str2 \
      "This is line 3" ;

請提出一種方法來做到這一點。

有幾種方法。 一個簡單的解決方案是添加括號:

strz = ("This is a line" +
       str1 +
       "This is line 2" +
       str2 +
       "This is line 3")

如果您希望每個“行”在單獨的行上,您可以添加換行符:

strz = ("This is a line\n" +
       str1 + "\n" +
       "This is line 2\n" +
       str2 + "\n" +
       "This is line 3\n")

Python 不是 php,您無需將$放在變量名之前。

a_str = """This is a line
       {str1}
       This is line 2
       {str2}
       This is line 3""".format(str1="blabla", str2="blablabla2")

使用格式化字符串的 Python 3 解決方案

Python 3.6 開始,您可以使用所謂的“格式化字符串”(或“f 字符串”)輕松地將變量插入到您的字符串中。 只需在字符串前面添加一個f並將變量寫入大括號 ( {} ) 中,如下所示:

>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'

要將長字符串拆分為多行,請使用括號( () ) 或使用多行字符串(由三個引號"""'''而不是一個引號包圍的字符串)。

1. 解決方案:括號

在字符串周圍加上括號,您甚至可以將它們連接起來,而無需在它們之間使用+符號:

a_str = (f"This is a line \n{str1}\n"
         f"This is line 2 \n{str2}\n"
         "This is line 3") # no variable here, so no leading f

很高興知道:如果一行中沒有變量,則該行不需要前導f

高興知道:您可以在每行末尾使用反斜杠 ( \\ ) 存檔相同的結果,而不是用括號括起來,但因此,對於PEP8,您應該更喜歡用括號來繼續行:

通過將表達式括在括號中,可以將長行分成多行。 這些應該優先於使用反斜杠進行行延續。

2. 解決方案:多行字符串

在多行字符串中,您不需要顯式插入\\n ,Python 會為您處理:

a_str = f"""This is a line
        {str1}
        This is line 2
        {str2}
        This is line 3"""

很高興知道:只要確保正確對齊代碼,否則每行前面都會有前導空格。


順便說一句:你不應該調用你的變量str因為那是數據類型本身的名稱。

格式化字符串的來源:

我會添加我需要連接到列表的所有內容,然后在換行符處加入它。

my_str = '\n'.join(['string1', variable1, 'string2', variable2])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM