详解Python3 定义一个跨越多行的字符串的多种方法

(编辑:jimmy 日期: 2024/9/22 浏览:2)

 方法一:使用三引号

> 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. 
起风了,唯有努力生存。
(纵有疾风起,人生不言弃。)

编辑的时候,引号挺对的,但是不知道为什么发布的时候,第一行的引号总是多了一些,其实应该是下面这样的:

详解Python3 定义一个跨越多行的字符串的多种方法

此种情况适用于想要多行表示某一多行字符串,实质上字符串是多行。

再举一个例子

> """
  <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", "Using Python Variables in HTML in multiline Python string", "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.起风了,唯有努力生存。(纵有疾风起,人生不言弃。)'

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。