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 and concatenates all elements of the sequence together and returns 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));

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 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 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. The following example gets the 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