Python String join() Method
join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
Syntax:
string_name.join(iterable)
Parameters:
string_name- It can be any string, character, digit or special character.
The join() method takes iterable – objects capable of returning their 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 1: Working of join() method
Python
# Python program to demonstrate the # use of join function to join list # elements with a character. list1 = [ '1' , '2' , '3' , '4' ] s = "-" # joins elements of list1 by '-' # and stores in string s s = s.join(list1) # join use to join a list of # strings to a separator s print (s) |
Output:
1-2-3-4
Example 2: Joining with an empty string
Python
# Python program to demonstrate the # use of join function to join list # elements without any separator. # Joining with empty separator list1 = [ 'g' , 'e' , 'e' , 'k' , 's' ] print ("".join(list1)) |
Output:
geeks
Example 3: Joining String with multiple parameters
Python3
#Joining string character to string 'S' .join( '12345' ) #Joining special symbols with string '()' .join( '12345' ) #Joining digits with string '100' .join( 'Geeks' ) #Joining special character with dictionary '_' .join({ 'Geek' : 1 , 'For' : 2 , 'Geeks' : 3 }) |
Output:
'1S2S3S4S5' '1()2()3()4()5' 'G100e100e100k100s' 'Geek_For_Geeks'
Note: When joining a string with a dictionary, it will join with the keys of a dictionary, not with values.