Python字符串拼接

今天总结一下Python中字符串拼接的方法:

  • 符号“+”拼接
  • 符号“%”拼接
  • join()方法拼接
  • foamat()方法拼接
  • string模块内的Template对象拼接

1.使用符号"+"拼接 

#定义一个字符
var = 'xiaoming'

str1 = var+'is a shy boy'     #前面拼接

str2 = 'i think'+var+'is shy' #中间拼接

str3 = 'the shy boy is '+var #末尾拼接

虽然使用该方法也可以拼接字符串,但它的效率很低,不建议使用。

2.使用符号"%"拼接

  • 单个字符
str = 'hello %s' %'world'
输出结果:hello world
  • 多个字符使用元组
str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3) 
注意:%s按照顺序拼接
  • 多个字符使用字典
 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

操作字典

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的位置
  • 字典参数
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'

猜你喜欢

转载自www.cnblogs.com/jim0816/p/9637420.html