
join()是一个字符串方法,它返回与iterable元素连接在一起的字符串。
join()方法提供了一种灵活的方式来连接字符串。它将可迭代的每个元素(如列表,字符串和元组)连接到字符串,并返回连接后的字符串。
join()的语法为:
string.join(iterable)
join()参数
join()方法采用一个可迭代的对象-能够一次返回其成员的对象
可迭代的一些示例是:
join()返回值
join()方法返回一个与iterable元素串联的字符串。
如果Iterable包含任何非字符串值,则将引发TypeError异常。
示例1:join()方法如何工作?
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))
numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))
s1 = 'abc'
s2 = '123'
""" s2的每个字符都连接到s1的前面""" 
print('s1.join(s2):', s1.join(s2))
""" s1的每个字符都连接到s2的前面""" 
print('s2.join(s1):', s2.join(s1))运行该程序时,输出为:
1, 2, 3, 4 1, 2, 3, 4 s1.join(s2): 1abc2abc3 s2.join(s1): a123b123c
示例2:join()方法如何用于集合?
test =  {'2', '1', '3'}
s = ', '
print(s.join(test))
test = {'Python', 'Java', 'Ruby'}
s = '->->'
print(s.join(test))运行该程序时,输出为:
2, 3, 1 Python->->Ruby->->Java
注意: 集合是项目的无序集合,您可能会获得不同的输出。
示例3:join()方法如何用于字典?
test =  {'mat': 1, 'that': 2}
s = '->'
print(s.join(test))
test =  {1:'mat', 2:'that'}
s = ', '
# 这抛出了错误
print(s.join(test))运行该程序时,输出为:
mat->that Traceback (most recent call last): File "...", line 9, in <module> TypeError: sequence item 0: expected str instance, int found
join()方法尝试将字典的键(而非值)连接到字符串。如果字符串的键不是字符串,则会引发TypeError异常。
