Python - String Method - join() Tutorial
This method will return a concatenated string by joining all the items of an iterable datatype such as List, String, Tuple, Set & Dictionary. i.e the element which is separated by a string separator
Syntax-
Separator.join(String)
#Separator - It is a string or character with which the iterable item needs to separated.
Example-
str1 = ['Hello', 'Python', 'Hello', 'World'] #List Join
print(" ".join(str1))
str2 = ('Hello', 'Python', 'Hello', 'World') #Tuple Join
print("-".join(str2))
str3 = 'Hello'
str4 = '123'
# each element of str3 is separated by str4
# '1'+ 'Hello'+ '2'+ 'Hello'+ '3'
print(str3.join(str4))
str5 = {'Hello', 'Python', 'Hello', 'World'} #Set
#Set doesn't allow duplicate value. Each time it will give random value
print("*".join(str5))
str6 = {'a':'Hello','b':'Python'} #Dictionary Join
# It will join only key with string datatype
print("->".join(str6))
str7 = {1:'Hello',1:'Python'} #Dictionary Join
# It will join only key with string datatype
print("->".join(str7))
Output-
Hello Python Hello World
Hello-Python-Hello-World
1Hello2Hello3
Hello*Python*World
a->b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6176/3662768156.py in <module>
21 str7 = {1:'Hello',1:'Python'} #Dictionary Join
22 # It will join only key with string datatype
---> 23 print("->".join(str7))
24
25
TypeError: sequence item 0: expected str instance, int found