Python中的join()函数

在本文中,我们将学习如何Join()在Python 3.x中实现功能。或更早。

让我们看看可迭代列表上最通用的实现。在这里,我们通过定界符连接列表的元素。分隔符可以是任何字符,也可以不是。

示例

# iterable declared
list_1 = ['t','u','t','o','r','i','a','l']

s = "->" # delimeter to be specified

# joins elements of list1 by '->'
print(s.join(list_1))

输出结果

t->u->t->o->r->i->a->l

现在,我们使用一个空的定界符来联接列表的元素。

示例

# iterable declared
list_1 = ['t','u','t','o','r','i','a','l']

s = "" # delimeter to be specified

# joins elements of list1 by ''
print(s.join(list_1))

输出结果

tutorial

现在,让我们采用另一种可迭代的方式,即字典,然后尝试将其键连接在一起。

示例

# iterable declared
dict_1 = {'t':'u','t':'o','r':'i','a':'l'}
dict_2 = { 1:'u', 2:'o', 3:'i', 4:'l'}

s = " " # delimeted by space

# joins elements of list1 by ' '
print(s.join(dict_1))
print(s.join(dict_2))

输出结果

T r a
-------------------------------------------------------------
TypeError

我们还可以类似的方式处理另一组可迭代对象。

结论

在本文中,我们学习了join()Python 3.x中的函数及其应用。或更早。