全球最实用的IT互联网信息网站!

AI人工智能P2P分享&下载搜索网页发布信息网站地图

当前位置:诺佳网 > AI人工智能 > AI通用技术 >

python字符串拼接方式了解

时间:2017-12-06 10:09

人气:

作者:admin

标签: python 

导读:python字符串拼接方式了解-python字符串拼接的方式 在Python的实际开发中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天总结一下: 用+符号拼接 用%符号拼接 用join()方法拼...

python字符串拼接的方式

在Python的实际开发中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天总结一下:

用+符号拼接

用%符号拼接

用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)

还可以指定参数对应位置:

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) 用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) #如果缺少参数,或报错如果使用safe_substitute()方法不会 str.safe_substitute(fruit1=fruit1,fruit2=fruit2) #输出'There are apples, bananas, ${fruit3} on the table'

总结

拼接的方法有多种,不同场合下使用不同的方法,个人比较推荐%、format()方法,简单方便

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信