python字符串拼接方式了解
python字符串拼接的方式
在Python的實際開發(fā)中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天總結(jié)一下:
用+符號拼接
用%符號拼接
用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ù)對應(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對象用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'總結(jié)
拼接的方法有多種,不同場合下使用不同的方法,個人比較推薦%、format()方法,簡單方便