Python字符串拼接
今天总结一下Python中字符串拼接的方法:
- 符号“+”拼接
- 符号“%”拼接
- join()方法拼接
- foamat()方法拼接
- string模块内的Template对象拼接
1.使用符号"+"拼接
1 2 3 4 5 6 7 8 | #定义一个字符 var = 'xiaoming' str1 = var + 'is a shy boy' #前面拼接 str2 = 'i think' + var + 'is shy' #中间拼接 str3 = 'the shy boy is ' + var #末尾拼接<br><br> |
虽然使用该方法也可以拼接字符串,但它的效率很低,不建议使用。
2.使用符号"%"拼接
- 单个字符
1 | str = 'hello %s' % 'world' 输出结果:hello world |
- 多个字符使用元组
1 | str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3) 注意: % s按照顺序拼接 |
- 多个字符使用字典
1 | str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % { 'fruit1' :fruit1, 'fruit2' :fruit2, 'fruit3' :fruit3} |
3.使用join()方法拼接
str.join(元组、列表、字典、字符串) 之后生成的只能是字符串。
str为插入每个字符单元间的字符,可以为空。如下:
操作元组
str = "-"; seq = ("a", "b", "c"); # 字符串序列 print str.join( seq );
输出:
a-b-c
操作列表
list=['1','2','3','4','5'] print(''.join(list))
结果:12345
操作字典
1 2 | seq = { 'hello' : 'nihao' , 'good' : 2 , 'boy' : 3 , 'doiido' : 4 } print ( '-' .join(seq)) #字典只对键进行连接 |
输出: hello-good-boy-doiido
拓展:python中还应注意os.path.join()函数,该函数语法: os.path.join(path1[,path2[,......]]),作用:将多个路径组合后返回
4.使用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的位置
- 字典参数
1 2 | str = 'There are {fruit1}, {fruit2}, {fruit3} on the table' str . format (fruit1 = fruit1,fruit2 = fruit2,fruit3 = fruit3) |
5.使用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'
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步