Python String join() 方法获取由给定分隔符分隔的可迭代对象中的所有元素(例如 list、string、tuple)并将它们连接成一个字符串。
分隔符表示用于分隔给定字符串的分隔符。这些分隔符可以是 ()、[]、{} 、 ; 等。
例如,在可迭代的 “['6', '8', '9']” 中,如果我们提供分隔符 “-”,那么连接后的字符串就变成了 “6-8-9”。
语法
以下是 Python String join() 方法的语法:
str.join(sequence)
参数
- sequence − 这是需要连接的元素序列。
返回值
此方法返回一个字符串,该字符串是可迭代对象中字符串的串联。元素之间的分隔符是提供此方法的字符串。
特例:如果 iterable 由任何非字符串值(包括 byte 对象)组成,则会引发 TypeError 异常。
例下面是一个示例,其中使用带有分隔符 “-” 的 Python String join() 方法连接字符串序列。然后返回结果:
s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
以下是上述代码的输出:
a-b-c
例
在下面的示例中,使用单词 “MATCH” 作为分隔符,将给定字典中的所有项目联接到一个字符串中:
Dictionary = {"Player":"Sachin Tendulkar", "Sports":"Cricket"}
# Providing the separator
sep = "MATCH"
# Joining the items in the dictionary with the given string
res = sep.join(Dictionary)
print(res)
上述代码的输出如下:
PlayerMATCHSports
注意:join() 方法将使用字符串分隔符连接字典的键,而不是值。
例在下面给出的示例中,Python 字符串 join() 方法用于连接字符 “#” 的集合。由于该集合只允许唯一值,因此只从重复的值中打印出一个值(在本例中为 '9'):
sets = {'9','7', '2','9','3','9'}
character = "#"
# storing in the string
res = character.join(sets)
print(res)
在执行上述代码时,我们得到以下输出:
2#3#7#9
例
在下面的示例中,引发 TypeError,因为可迭代对象的元素不在 string 中:
numbers = (3,6,7,4,7,4,5,32,98,35)
char = "*"
print (char.join(numbers))
当我们运行上述程序时,它会产生以下错误:
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in
print (char.join(numbers))
TypeError: sequence item 0: expected str instance, int found
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in
print (char.join(numbers))
TypeError: sequence item 0: expected str instance, int found