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()方法,简单方便
通过CPLD的编码器解码接口、PWM输出设计
为什么处理器这么耗电,该如何解决
如何从TI新的全集成变压器技术中获益
低温循环水槽(高精度)的产品特点是什么
开源大模型Falcon(猎鹰) 180B发布 1800亿参数
python字符串拼接方式了解
中小企业请收藏丨轻量应用服务器企业选购避坑指南
贾跃亭 FF 将通过 SPAC 合并上市,FF 91 或一年后上市
好奇心对于学习人工智能有帮助吗
SpaceX星链卫星互联网用户已超10000名
Apollo定义生态 开发者定义未来
PebbleTime评测 GameBoy一样的情怀屏幕
中国高端医疗器械依赖进口,广东已逐渐形成医疗器械产业集群
苹果AR/VR头显相关专利:利用光学标记定位目标物体
美国政府发布中国通讯产品封杀令 商务部认为这是一种错误信号
单片机的两大系列进行PK_MSP430和AVR
泄洪预警水库水电站泄洪预警解决方案
如何选择好的LED显示屏模组套件
OPPOR11推出王者荣耀定制版即将上市
音圈模组助力的3D打印设计大赛