Python字符串拼接
在Python的实际开发中,很多都需要用到字符串拼接,Python中字符串拼接有很多,今天总结一下:
- 用
+符号拼接 - 用
%符号拼接 - 用
join()方法拼接 - 用
format()方法拼接 - 用
string模块中的Template对象
如果还有其他方法,欢迎补充。
例子:
|
|
要求:
输出字符串’There are apples, bananas, pears on the table’
1. 用+符号拼接
用+拼接字符串如下:str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'
该方法效率比较低,不建议使用
2. 用%符号拼接
用%符号拼接方法如下:
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}
该方法比较通用
3. 用join()方法拼接
join()`方法拼接如下
|
|
该方法使用与序列操作
4. 用format()方法拼接
用format()方法拼接如下:
|
|
还可以指定参数对应位置:
|
|
同样,也可以使用字典:
|
|
5. 用string模块中的Template对象
用string模块中的Template对象如下:
|
|
总结
拼接的方法有多种,不同场合下使用不同的方法,个人比较推荐%、format()方法,简单方便。