詳解Python3 定義一個跨越多行的字串的多種方法
阿新 • • 發佈:2020-09-08
方法一:使用三引號
>>> str1 = '''Le vent se lève,il faut tenter de vivre. 起風了,唯有努力生存。 (縱有疾風起,人生不言棄。)''' >>> str1 'Le vent se lève,il faut tenter de vivre. \n起風了,唯有努力生存。\n(縱有疾風起,人生不言棄。)' >>> print(str1) Le vent se lève,il faut tenter de vivre. 起風了,唯有努力生存。 (縱有疾風起,人生不言棄。)
編輯的時候,引號挺對的,但是不知道為什麼釋出的時候,第一行的引號總是多了一些,其實應該是下面這樣的:
此種情況適用於想要多行表示某一多行字串,實質上字串是多行。
再舉一個例子
>>> """ <div class="AuthorInfo-content"> <div class="AuthorInfo-head"> <span class="UserLink AuthorInfo-name"> <div class="Popover"> <div id="Popover222-toggle" aria-haspopup="true" aria-expanded="false" aria-owns="Popover222-content"> 作者:<a class="UserLink-link" data-za-detail-view-element_name="User" target="_blank" href="{0}" rel="external nofollow" rel="external nofollow" >{1}</a> </div> </div> </span> </div> <div class="AuthorInfo-detail"> <div class="AuthorInfo-badge"> <div class="AuthorInfo-badgeText"> 簽名:{2} </div> </div> </div> </div> <br/> """.format("https://stackoverflow.com/questions/45624449","Using Python Variables in HTML in multiline Python string","123")
再舉一個用 f-string 格式化的例子,參考https://realpython.com/python-f-strings/
>>> """ <div class="AuthorInfo-content"> <div class="AuthorInfo-head"> <span class="UserLink AuthorInfo-name"> <div class="Popover"> <div id="Popover222-toggle" aria-haspopup="true" aria-expanded="false" aria-owns="Popover222-content"> 作者:<a class="UserLink-link" data-za-detail-view-element_name="User" target="_blank" href="{0}" rel="external nofollow" rel="external nofollow" >{1}</a> </div> </div> </span> </div> <div class="AuthorInfo-detail"> <div class="AuthorInfo-badge"> <div class="AuthorInfo-badgeText"> 簽名:{2} </div> </div> </div> </div> <br/> """.format("https://stackoverflow.com/questions/45624449","123")
下面的兩種方法主要適用於一個長字串一行表示不下,多行表示更為美觀,實質上字串還是一行。
方法二:使用反斜槓
>>> name = "Eric" >>> profession = "comedian" >>> affiliation = "Monty Python" >>> message = f""" ... Hi {name}. ... You are a {profession}. ... You were in {affiliation}. ... """ ... >>> message '\n Hi Eric.\n You are a comedian.\n You were in Monty Python.\n'
方法三:使用小括號
>>> str3 = ('Le vent se lève,il faut tenter de vivre.' '起風了,唯有努力生存。' '(縱有疾風起,人生不言棄。)') >>> str3 'Le vent se lève,il faut tenter de vivre.起風了,唯有努力生存。(縱有疾風起,人生不言棄。)'
到此這篇關於詳解Python3 定義一個跨越多行的字串的多種方法的文章就介紹到這了,更多相關Python3 跨越多行的字串內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!