join函数
语法
str.join(sequence)
参数
sequence: 要连接的元素序列
实例一
连接字符串
str1 = '-'
seq1 = ('a','b','c')
print(str1.join(seq1)) # a-b-c
实例二
连接数组(数组元素为字符串)
str2 = '*'
seq2 = ['a','b','c']
print(str2.join(seq2)) # a*b*c
实例三
连接数组(数组元素为数字)
错误示范:会触发TypeError: sequence item 0: expected string, int found的错误
str3 = '*'
seq3 = [1,2,3]
# TypeError: sequence item 0: expected str instance, int found
print(str3.join(seq3))
正确的示范:
str3 = '*'
seq3 = [1,2,3]
seq4 = []
for i in range(len(seq3)):
seq4.append(str(seq3[i]))
print(str3.join(seq4)) # 1*2*3
print(str3.join(str(i) for i in seq4)) # 1*2*3