您的位置:

21. Python join()

Python join()

更新:

python 中的join()函数通过使用字符串分隔符连接给定 iterable 的所有元素来帮助创建新字符串。

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

join()参数:

join()函数接受一个参数。如果可迭代表包含任何非字符串值,该函数将引发类型错误异常,

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

join()返回值

返回值始终是串联字符串。如果我们使用字典作为可迭代表,返回值将是键,而不是值。

| 投入 | 返回值 | | 可重复的 | 线 |

Python 中join()方法的示例

示例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 

示例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) 

示例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 <module>TypeError: sequence item 0: expected str instance, int found</module>