join()是一個(gè)字符串方法,它返回與iterable元素連接在一起的字符串。
join()方法提供了一種靈活的方式來連接字符串。它將可迭代的每個(gè)元素(如列表,字符串和元組)連接到字符串,并返回連接后的字符串。
join()的語法為:
string.join(iterable)
join()方法采用一個(gè)可迭代的對象-能夠一次返回其成員的對象
可迭代的一些示例是:
join()方法返回一個(gè)與iterable元素串聯(lián)的字符串。
如果Iterable包含任何非字符串值,則將引發(fā)TypeError異常。
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))
numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))
s1 = 'abc'
s2 = '123'
""" s2的每個(gè)字符都連接到s1的前面"""
print('s1.join(s2):', s1.join(s2))
""" s1的每個(gè)字符都連接到s2的前面"""
print('s2.join(s1):', s2.join(s1))運(yùn)行該程序時(shí),輸出為:
1, 2, 3, 4 1, 2, 3, 4 s1.join(s2): 1abc2abc3 s2.join(s1): a123b123c
test = {'2', '1', '3'}
s = ', '
print(s.join(test))
test = {'Python', 'Java', 'Ruby'}
s = '->->'
print(s.join(test))運(yùn)行該程序時(shí),輸出為:
2, 3, 1 Python->->Ruby->->Java
注意: 集合是項(xiàng)目的無序集合,您可能會獲得不同的輸出。
test = {'mat': 1, 'that': 2}
s = '->'
print(s.join(test))
test = {1:'mat', 2:'that'}
s = ', '
# 這拋出了錯(cuò)誤
print(s.join(test))運(yùn)行該程序時(shí),輸出為:
mat->that Traceback (most recent call last): File "...", line 9, in <module> TypeError: sequence item 0: expected str instance, int found
join()方法嘗試將字典的鍵(而非值)連接到字符串。如果字符串的鍵不是字符串,則會引發(fā)TypeError異常。