join() function in Python


In this article, we will learn about how we can implement Join() function in Python 3.x. or earlier.

Let’s see the most general implementation over the list iterable. Here we join the elements of a list via a delimiter. A delimiter can be any character or nothing.

Example

# 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))

Output

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

Now we are using an empty delimiter to join the elements of a list.

Example

# 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))

Output

tutorial

Now let’s take another type of iterable i.e. dictionary and try and joining its keys together.

Example

# 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))

Output

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

We can also work on another set of iterables in a similar manner.

Conclusion

In this article, we learned about join() function and its application in Python 3.x. Or earlier.

raja
Published on 07-Aug-2019 08:12:43
Advertisements