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.
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))
'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.
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))
'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
nums = (1, 2, 3, 4, 5)
print(','.join())
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.
emp = {'Steve': 1, 'Bill': 2, 'Ravi': 3 }
print('>-'.join(emp))
emp = {1:'Steve', 2:'Bill', 3:'Ravi' } # raise an error
print('>-'.join(emp))
Steve>-Bill>-Ravi
TypeError: sequence item 0: expected str instance, int found