Methods and Functions

Python String Join()

Python join() provides the functionality of joining elements from the iterable separated by a string operator. A built-in function called Python join is used to return a string of iterators in which the elements of the sequence are being joined by a string separator.

There arises a situation in which we would want to print data values of the iterable all together by adding an element in between them to make some sense out of it. Python tackles this situation by providing us a built-in function known as Python join() function. The Python join() function is used to join all the elements from the iterable and create a string and return it as an output to the user. Python join() returns a new string which is the concatenation of the other strings in the iterable specified. We will understand more about Python join() function in the article below.

python join

Python join

Python’s built-in join() function provides an efficient and easy way of joining every element of the iterable (list, tuple, dictionary, set) and using a string separator in order to separate the values. This join() function creates and returns a concatenated string. The syntax for Python join() function is as below:

Syntax

                    

string.join(iterable)

where,

iterable = lists, strings, tuples, dictionary, sets

string = string operator used to separate the iterables

Let us look at a simple example where we join the string values of a list using Python’s string join() function. According to the syntax, we specify the string separator and then use it with join() function in order to return a concatenated output.

Example

                    

numlist = ['1', '3', '5', '7', '9']
separator = ' -> '

print('List before Join():', numlist)
print('List after Join():' , separator.join(numlist))

Output

                    

List before Join(): ['1', '3', '5', '7', '9']
List after Join(): 1 -> 3 -> 5 -> 7 -> 9

Return Value from join python method

The join() function returns a string which is created by joining the data elements of an iterable by specifying the string separator. If the iterable contains any non-string data elements, then the join() function will give a TypeError exception.

Note – The iterable must contain string value data elements in order to use the python join() function.

Example

                    

numlist = [1, 3, 5, 7, 9]
separator = ', '

print(separator.join(numlist))

Output

                    

Traceback (most recent call last):
File "", line 3, in 
TypeError: sequence item 0: expected str instance, int found

Notice here that the iterable ‘numlist’ does not contain string value data elements. In order to avoid this, we could pass the values in the iterable as [‘1’, ‘3’, ‘5’, ‘7’, ‘9’].

Working of join in Python

Example 1

                    

# .join with lists
words = ['Hello','can','we', 'play', 'today', '!']

sentence = ' '.join(words)
print(sentence)

Output

                    

Hello can we play today !

Example 2

                    

# .join with string
str1 = 'XYZ'
str2 = '1234'

print(str1.join(str2))
print(str2.join(str1))

string = 'Hello'
print('.'.join(string))

Output

                    

1XYZ2XYZ3XYZ4
X1234Y1234Z

H.e.l.l.o

The join Method Python with Sets

A set iterable is an unordered collection of data elements. Hence after running the program, we might get a different sequence of answers. Each time you run the program, the answer sequence will be changed.

Example

                    

set1 = {'Mumbai', 'Delhi', 'New York'}
a = ' -> '
print('Flight Route:', a.join(set1))

set2 = {'a', 'e', 'i', 'o', 'u'}
b = ''
print('Vowel characters are:', b.join(set2))

Output

                    

Flight Route: Mumbai -> Delhi -> New York
Vowel characters are: eiauo

The join() Method with Dictionaries

Dictionary is a type of iterable which consists of key-value pair of data items. The python join() function only joins the key part of the dictionary with the help of a string separator. It does not join the value part.

Note – If the key in the dictionary is not a string, then the join() function will throw a TypeError exception.

Example

                    

data = {'Age': 25, 'Mobile': 9876543210}   # key is a string
s = ' -> '.join(data)
print(s)

subj = {1: 'Science', 2: 'Maths', 3: 'English'}   # key isn’t a string & join() does not work on value attributes too
ss = '->'.join(subj)
print(ss)

Output

                    

Age -> Mobile

Traceback (most recent call last):
File "", line 6, in 
TypeError: sequence item 0: expected str instance, int found

FAQs on Python Join

Q1. What is the join() function in Python?

Answer. Python provides a built-in function known as join() function which is used to concatenate all the data values stored in the iterable using a string separator. It is necessary to provide the string separator while using the join() function. Also, all the data values stored must be of string type in order to successfully execute the python join() function.

Q2. How can you join words in Python?

Answer. To join words in Python, we use the join() function provided by Python. Its syntax is –

string.join(iterable)

Let us take an example to understand how to join words in Python.

Example

                    

my_list = ['P', 'y', 't', 'h', 'o', 'n']
s = ''.join(my_list)
print(s)

my_tuple = ('Hey,', 'how', 'are', 'you', '?')
a = ' '.join(my_tuple)
print(a)

Output

                    

Python
Hey, how are you ?

Here, we have provided an empty string separator in the first part and empty whitespace in order to separate each word of the tuple after joining.

Q3. How do you perform join in Python 3?

Answer. Python’s join() function is useable in any of the python versions. There is similar functionality and syntactical usage of join() function in Python version 3.x. Refer above example for more understanding.

Q4. How do you join a string in a list in Python?

Answer. Values in the list should be strictly of string data type. If it is so, then we can use the join() function in order to concatenate the data elements of the list.

Example

                    

# to join strings in a list
my_list = ['How', 'is', 'the', 'weather', 'today', '?']
s = ' '.join(my_list)
print(s)

car_type = ['SUV', 'XUV', 'Hatchback', 'Sedan', 'Sports', 'Coupe']
a = ' -> '.join(car_type)
print(a)

Output

                    

How is the weather today ?
SUV -> XUV -> Hatchback -> Sedan -> Sports -> Coupe

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.