top of page

Python Tutorial

Public·1 member

Join function in Python

Python join list elements with separator


Join function is most useful in python which adds all items of list into a string by a specified separator


The join() is a string method which returns a string concatenated with the elements of an iterable.


Example 1:

# list of words
words = ['This','is','a','sentence']

#delimiter to seperate each word
seperator = ' '

#concat all together
sentence = seperator.join(words)
print(sentence) 

output: This is a sentence


Parameters: The join() method takes iterable – objects capable of returning its members one at a time.


Some examples are List, Tuple, String, Dictionary and Set


Return Value: The join() method returns a string concatenated with the elements of iterable.


Type Error: If the iterable contains any non-string values, it raises a TypeError exception.


Example 2: Join method is useful when you are reading file


Here is student.csv file data


stud_id,firstname,middlename,lastname 1, Jitendra, kumar, Singh 2, Aman, Kumar, Singh


file = open('student.csv')
line = file.readLine()

while line:
    words = line.split(',')
    # adding only last three fields
    fullName = " ".join(words[1:])
    print(fullName)
output: Jitendra kumar singh
        Aman kumar Singh

Hope this will be helpful


please comment below if you have any doubts or want to share something related to this.
19 Views
bottom of page