Python String join() Method

The join() method returns a string, which is the concatenation of the string (on which it is called) with the string elements of the specified iterable as an argument.

Syntax:

str.join(iterable)

Parameters:

iterable: (Required) An iterable object such as list, tuple, string, set, dict.

Return Value:

Returns a string.

The following example demonstrates the join() method.

Example: join()
sep = ','
names = ['Steve', 'Bill', 'Ravi', 'Jonathan'] # list
print(sep.join(names))

mystr = 'Hello' # string
print(sep.join(mystr))

nums = ('1', '2', '3', '4') # tuple
print(sep.join(nums))

langs = {'Python', 'C#', 'Java', 'C++'} # set
print(sep.join(langs))
Output
'Steve,Bill,Ravi,Jonathan'
'H,e,l,l,o'
'1,2,3,4'
'Python,C#,Java,C++'

The seperator string can be of any length or char, as shown below.

Example: join()
sep = 'õ' # Unicode seperator
names = ['Steve', 'Bill', 'Ravi', 'Jonathan'] # list
print(sep.join(names))

sep = '-->'
mystr = 'Hello' # string
print(sep.join(mystr))

sep = '****'
nums = ('1', '2', '3', '4') # tuple
print(sep.join(nums))
Output
'SteveõBillõRaviõJonathan'
'H-->e-->l-->l-->o'
'1****2****3****4'

The elements of an iterable must be string elements, otherwise it will raise a TypeError

Example: join() with Numbers
nums = (1, 2, 3, 4, 5)
print(','.join())
Output
Traceback (most recent call last):
    ','.join((1,2,3,4,5))
TypeError: sequence item 0: expected str instance, int found

The join() Method with Dictionary

The join() method concatenates the keys. If keys are not strings, then it will raise a TypeError.

Example: join() with Dictionary
emp = {'Steve': 1, 'Bill': 2, 'Ravi': 3 }
print('>-'.join(emp))

emp = {1:'Steve', 2:'Bill', 3:'Ravi' } # raise an error
print('>-'.join(emp))
Output
Steve<-Bill<-Ravi
TypeError: sequence item 0: expected str instance, int found
Want to check how much you know Python?