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

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

python字符串拼接的方式

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

用+符號(hào)拼接

用%符號(hào)拼接

用join()方法拼接

用format()方法拼接

用string模塊中的Template對(duì)象

例子:

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

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

用+符號(hào)拼接

用+拼接字符串如下:

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

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

用%符號(hào)拼接

用%符號(hào)拼接方法如下:

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ù)對(duì)應(yīng)位置:

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對(duì)象

用string模塊中的Template對(duì)象如下:

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

總結(jié)

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

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