How to use String Join() function in Python?


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

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

The following example uses the join method over a list of characters to create a string out of it.

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

Concatenate Strings in a List using the Join() method.

Although concatenation of string is a trivial operation in Python, here we will show how we create a bigger string from multiple smaller strings using Join. For example, the address details of an employee are stored in a list, where each element in the list is a subsection of the full address. The company needs to create a full address to post a letter.

We will use a separator "," while creating a bigger string.

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

How the Join () works over the 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 each element is a key, value pair format in a dictionary. So what will be the output of the 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);
name,city,Country

The output contains only the key names. The following example gets the values only.

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

How do you add both (key and value) to 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);
name:Johncity:CambridgeCountry:UK