Python String join() function

How to use String Join() function in Python?


The join() function works over an iterable object such as tuple, list, etc. An iterable object may have multiple elements of similar or different types. As the name suggests, the join() function concatenates all elements of a sequence (passed as an argument) together and returns the string.

The function is a method of string class. The string object that calls the method works as a separator between the elements in the final output.

In the following example we are using join method over a list of characters to create the string.

 myList = ['c','s','p','s','p','r','o','t','o','c','o','l'];
 seaprator="";
 print(" String after Join = ", seaprator.join(myList));

Output->

String after Join =  cspsprotocol

Concatenate Strings in a List using Join()

Although concatenation of string is a trivial operation in Python, here we will show how we create a bigger string from multiple small strings? For example, the address details of a person are stored in a list, the company needs to create a full address for a letter post.

We will use separate “,” while creating a bigger string.

 personDetail = ['John' , 'Lane 24', 'Cambridge', 'UK'];
 seap=',';
 print("Full address = ",  seap.join(personDetail));

Output->

Full address =  John,Lane 24,Cambridge,UK

How Join() works over Python dictionary?

In previous examples, we were using the list. Each element in a list have a single literal, so it is easy to guess the output of the join() function over the list object.

But in a dictionary, each element is a key, value pair format. So what will be the output of join? All concatenated keys, values, or both? Let’s check with the examples.

myDict = {'name':'John', 'city':'Cambridge', 'Country':'UK'};
 result = ','.join(myDict);
 print(result);

Output->

name,city,Country

The output contains only the key names. Following example gets he values only.

 myDict = {'name':'John', 'city':'Cambridge', 'Country':'UK'};
 result = ','.join(myDict.values());
 print(result);

Output->

John,Cambridge,UK

How to add both (key and value) in the string with join?

myDict = {'name':'John', 'city':'Cambridge', 'Country':'UK'};
 result="";
 for (key,val) in myDict.items():
 result = result + "".join(":".join((key,val)));
 print(result);

Output->

name:Johncity:CambridgeCountry:UK