字符串 join()
方法通过连接可迭代对象(列表、字符串、元组)的所有元素并用给定的分隔符分隔,返回一个字符串。
示例
text = ['Python', 'is', 'a', 'fun', 'programming', 'language']
# join elements of text with space
print(' '.join(text))
# Output: Python is a fun programming language
字符串 join() 的语法
join()
方法的语法是
string.join(iterable)
join() 参数
join()
方法将一个可迭代对象(能够一次返回其成员的对象)作为其参数。
一些可迭代对象的例子有
注意:join()
方法提供了一种灵活的方式来从可迭代对象创建字符串。它通过一个字符串分隔符(调用 join()
方法的字符串)连接可迭代对象(如列表、字符串和元组)的每个元素,并返回连接后的字符串。
join() 的返回值
join()
方法返回一个通过给定字符串分隔符连接可迭代对象元素而创建的字符串。
如果可迭代对象包含任何非字符串值,它会引发 TypeError
异常。
示例 1:join() 方法的工作原理
# .join() with lists
numList = ['1', '2', '3', '4']
separator = ', '
print(separator.join(numList))
# .join() with tuples
numTuple = ('1', '2', '3', '4')
print(separator.join(numTuple))
s1 = 'abc'
s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2
# 'a'+ '123'+ 'b'+ '123'+ 'b'
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() 方法
# .join() with sets
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() 方法
# .join() with dictionaries
test = {'mat': 1, 'that': 2}
s = '->'
# joins the keys only
print(s.join(test))
test = {1: 'mat', 2: 'that'}
s = ', '
# this gives error since key isn't string
print(s.join(test))
输出
mat->that Traceback (most recent call last): File "...", line 12, in <module> TypeError: sequence item 0: expected str instance, int found
join()
方法尝试使用字符串分隔符连接字典的键(而非值)。
注意:如果字符串的键不是字符串,它会引发 TypeError
异常。
另请阅读