日本黄色一级经典视频|伊人久久精品视频|亚洲黄色色周成人视频九九九|av免费网址黄色小短片|黄色Av无码亚洲成年人|亚洲1区2区3区无码|真人黄片免费观看|无码一级小说欧美日免费三级|日韩中文字幕91在线看|精品久久久无码中文字幕边打电话

當前位置:首頁 > 智能硬件 > 人工智能AI
[導讀] python字符串拼接的方式 在Python的實際開發(fā)中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天總結一下: 用+符號拼接 用%符號拼接 用

python字符串拼接的方式

在Python的實際開發(fā)中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天總結一下:

用+符號拼接

用%符號拼接

用join()方法拼接

用format()方法拼接

用string模塊中的Template對象

例子:

fruit1 = ‘apples’
fruit2 = ‘bananas’
fruit3 = ‘pears’

要求:
輸出字符串’There are apples, bananas, pears on the table’

用+符號拼接

用+拼接字符串如下:

str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'

該方法效率比較低,不建議使用

用%符號拼接

用%符號拼接方法如下:

str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)

除了用元組的方法,還可以使用字典如下:

str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3} 該方法比較通用 用join()方法拼接

join()`方法拼接如下

temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table'] ''.join(temp)

該方法使用與序列操作

用format()方法拼接

用format()方法拼接如下:

str = 'There are {}, {}, {} on the table' str.format(fruit1,fruit2,fruit3)

還可以指定參數(shù)對應位置:

str = 'There are {2}, {1}, {0} on the table' str.format(fruit1,fruit2,fruit3) #fruit1出現(xiàn)在0的位置

同樣,也可以使用字典:

str = 'There are {fruit1}, {fruit2}, {fruit3} on the table' str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) 用string模塊中的Template對象

用string模塊中的Template對象如下:

from string import Template str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table') #此處用的是{},別搞錯了哦 str.subsTItute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) #如果缺少參數(shù),或報錯如果使用safe_subsTItute()方法不會 str.safe_subsTItute(fruit1=fruit1,fruit2=fruit2) #輸出'There are apples, bananas, ${fruit3} on the table'

總結

拼接的方法有多種,不同場合下使用不同的方法,個人比較推薦%、format()方法,簡單方便

本站聲明: 本文章由作者或相關機構授權發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點,本站亦不保證或承諾內容真實性等。需要轉載請聯(lián)系該專欄作者,如若文章內容侵犯您的權益,請及時聯(lián)系本站刪除( 郵箱:macysun@21ic.com )。
換一批
延伸閱讀
關閉