Tutorial Study Image

Python join()

Python 中的 join() 函数通过使用字符串分隔符连接给定可迭代对象的所有元素来创建新字符串。


string.join(iterable) #where iterable may be List, Tuple, String, Dictionary and Set.
 

join() 参数

join() 函数只接受一个参数。如果可迭代对象包含任何非字符串值,该函数将引发 TypeError 异常。

参数 描述 必需/可选
可迭代对象 任何可迭代对象,其中所有返回的值都是字符串。 必需

join() 返回值

返回值始终是连接的字符串。如果我们将字典用作可迭代对象,返回的值将是键,而不是值。

 

输入 返回值
可迭代对象 字符串

Python 中 join() 方法的示例

示例 1:join() 方法在 Python 中如何工作?


# .join() with lists
List = ['5', '4', '3', '2']
separator = ', '
print(separator.join(List))

# .join() with tuples
Tuple = ('5', '4', '3', '2')
print(separator.join(Tuple))

string1 = 'xyz'
string2 = '123'

# each element of string2 is separated by string1
# '1'+ 'xyz'+ '2'+ 'xyz'+ '3'
print('string1.join(string2):', string1.join(string2))

# each element of string1 is separated by string2
# 'x'+ '123'+ 'y'+ '123'+ 'z'
print('string2.join(string1):', string2.join(string1))
 

输出


5, 4, 3, 2
5, 4, 3, 2
string1.join(string2): 1xyz2xyz3
string2.join(string1): x123y123z

示例 2:join() 方法如何与 Python 中的集合一起工作?


# .join() with sets
num = {'5', '4', '3'}
separator = ', '
print(separator.join(num))

string = {'Apple', 'Orange', 'Grapes'}
separator = '->->'
print(separator.join(string))
 

输出


5, 4, 3
Apple->->Orange->->Grapes

示例 2:传递超出范围的整数


print(chr(-1))
print(chr(1114112))
 

输出


ValueError: chr() arg not in range(0x110000) 
ValueError: chr() arg not in range(0x110000)

示例 3:join() 方法如何与字典一起工作?


# .join() with dictionaries
dict = {'test': 1, 'with': 2}
seperator = '->'

# joins the keys only
print(seperator.join(dict))

dict = {1: 'test', 2: 'with'}
seperator = ', '

# this gives error since key isn't string
print(seperator.join(dict))
 

输出


test->with
Traceback (most recent call last):
  File "...", line 12, in 
TypeError: sequence item 0: expected str instance, int found