python-字符串拼接
来源:互联网 发布:皮肤软件下载 编辑:程序博客网 时间:2024/05/16 02:04
Python字符串拼接
在Python的实际开发中,很多都需要用到字符串拼接,Python中字符串拼接有很多,今天总结一下:
- 用
+
符号拼接 - 用
%
符号拼接 - 用
join()
方法拼接 - 用
format()
方法拼接 - 用
string
模块中的Template
对象
如果还有其他方法,欢迎补充。
例子:
fruit1 = 'apples'fruit2 = 'bananas'fruit3 = 'pears'
要求:
输出字符串’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()`方法拼接如下
temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table']''.join(temp)
该方法使用与序列操作
4. 用format()
方法拼接
用format()
方法拼接如下:
str = 'There are {}, {}, {} on the table'str.format(fruit1,fruit2,fruit3)
还可以指定参数对应位置:
str = 'There are {2}, {1}, {0} on the table'str.format(fruit1,fruit2,fruit3) #fruit1出现在0的位置
同样,也可以使用字典:
str = 'There are {fruit1}, {fruit2}, {fruit3} on the table'str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3)
5. 用string
模块中的Template
对象
用string
模块中的Template
对象如下:
from string import Templatestr = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table') #此处用的是{},别搞错了哦str.substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) #如果缺少参数,或报错如果使用safe_substitute()方法不会str.safe_substitute(fruit1=fruit1,fruit2=fruit2) #输出'There are apples, bananas, ${fruit3} on the table'
总结
拼接的方法有多种,不同场合下使用不同的方法,个人比较推荐%
、format()
方法,简单方便。
1 0
- python字符串拼接
- python-字符串拼接
- python字符串拼接
- python字符串拼接
- python 合并拼接字符串
- Python字符串拼接
- python 字符串拼接、格式化
- python字符串拼接
- python分割和拼接字符串
- Python字符串和数字拼接
- Python合并(拼接) 字符串
- python字符串拼接速度对比
- 轻松python文本专题-拼接、合并字符串
- 【拼接最小字典序字符串】(python)
- Python中的字符串序列拼接方法
- Python字符串拼接的五种方式
- Python 字符串拼接、逻辑连接符
- python之Bug之字符串拼接bug
- MyEclipse SVN 插件
- 求子数组的最大和
- fedora22/ubuntu14.04下配置Trilinos/Anasazi,PETSc/SLEPc
- Android开发经验:成为高手必看的10个建议
- HDU 3849--By Recognizing These Guys, We Find Social Networks Useful【边双联通 && 求桥的数目 && 输出桥】
- python-字符串拼接
- Flume 1.6.0 User Guide
- 【套题】2015年百度之星程序设计大赛 - 初赛(1)
- Java覆盖和隐藏
- 7、其他权限管理命令
- Callable和Future、FutureTask
- C/C++ 之 ‘++’、‘+’、‘+=’、‘-’、‘()’、‘--’ 操作符的重载实现重载
- Rope大法(可持久化平衡树)
- Java多线程基础知识(四)