Python字符串拼接
在Python的實際開發中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天總結一下:
- 用
+
符號拼接 - 用
%
符號拼接 - 用
join()
方法拼接 - 用
format()
方法拼接 - 用
string
模塊中的Template
對象
如果還有其他方法,歡迎補充。
例子:
fruit1 = 'apples' fruit2 = 'bananas' fruit3 = 'pears'
要求:
輸出字符串’There are apples, bananas, pears on the table’
1. 用+
符號拼接
用+
拼接字符串如下:
1 str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'
該方法效率比較低,不建議使用
2. 用%
符號拼接
用%
符號拼接方法如下:
1 str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)
除了用元組的方法,還可以使用字典如下:
1 str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3}
該方法比較通用
3. 用join()
方法拼接
join()`方法拼接如下
1 temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table'] 2 ''.join(temp)
該方法使用與序列操作
4. 用format()
方法拼接
用format()
方法拼接如下:
4. 用format()
方法拼接
用format()
方法拼接如下:
1 str = 'There are {}, {}, {} on the table' 2 str.format(fruit1,fruit2,fruit3)
還可以指定參數對應位置:
1 str = 'There are {2}, {1}, {0} on the table' 2 str.format(fruit1,fruit2,fruit3) #fruit1出現在0的位置
同樣,也可以使用字典:
1 str = 'There are {fruit1}, {fruit2}, {fruit3} on the table' 2 str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3)
5. 用string
模塊中的Template
對象
用string
模塊中的Template
對象如下:
1 from string import Template 2 str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table') #此處用的是{},別搞錯了哦 3 str.substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) #如果缺少參數,或報錯如果使用safe_substitute()方法不會 4 str.safe_substitute(fruit1=fruit1,fruit2=fruit2) 5 #輸出'There are apples, bananas, ${fruit3} on the table'
總結
拼接的方法有多種,不同場合下使用不同的方法,個人比較推薦%
、format()
方法,簡單方便。