在Python中,经常需要对字符串进行拼接操作,这里整理了字符串拼接的一些常用方法。
第一种,使用+链接两个或多个字符串,如:
s1 = 'a'
s2 = 'b'
s3 = s1 + s2
print(s3)
输出: ab
第二种,把所有待连接的字符串放到一个列表中,然后使用join把它们连接在一起,如
s1 = 'a'
s2 = 'b'
s3 = ''.join([s1, s2])
print(s3)
输出:ab
建议:方法1会为每个待连接的字符串以及新产生的字符串分配新的内存,方法2则不会,因此方法2会节省内存。
第三种,利用format进行拼接 (从python 2.6开始)
''' 语法为 str.format(args,**kwargs) '''
# eg(1) {} 充当占位符
s = 'hello, {} {}'.format('张三', '李四')
print(s)
hello,张三 李四
# eg(2) {[index]} 按索引位置填充 .format([0]=value1, [1]= value1},)
s0 = 'hell0, {0},{1}'.format('张三', '李四')
s1 = 'hell0, {1},{0}'.format('张三', '李四')
print(s0)
输出:hello, 张三,李四
print(s1)
hello, 李四,张三
# eg(3) {[keyword]}
s = 'hell0, {a},{b}'.format(b='张三', a='李四')
print(s)
hello, 李四,张三
# eg(4) {[keyword,index]} keyword 放在最后
s = 'hell0, {1}{a}{0},{b}'.format('i0', 'i1', b='张三', a='李四')
print(s)
hello, i1李四i0,张三
# eg(5) format 参数类型不限,当为元祖,列表,集合,字典时输出
s = 'hell0, {b}'.format(b=['张三', '李四'])
print(s)
hello, ['张三','李四']
# eg(6) 作为函数使用
s = 'hello, {} {}'.format
word = s('张三', '李四')
print(s)
hello, 张三,李四
第四种,直接拼接法
print('hello''python')