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:
- 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: Joining with an empty string
Here, we join the list of elements using the join method.
Python3
# Joining with empty separator list1 = [ 'g' , 'e' , 'e' , 'k' , 's' ] print ("".join(list1)) # Joining with string list1 = " geeks " print ( "$" .join(list1)) |
Output:
geeks $g$e$e$k$s$
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 2: Joining String with lists using join()
Here, we join the tuples of elements using the join() method in which we can put any character to join with a string.
Python3
# elements in tuples list1 = ( '1' , '2' , '3' , '4' ) # put any character to join 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
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 3: Joining String with sets using join()
In this example, we are using a Python set to join the string.
Note: Set contains only unique value therefore out of two 4 one 4 is printed.
Python3
list1 = { '1' , '2' , '3' , '4' , '4' } # put any character to join 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-#-3-#-2-#-4
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 4: Joining String with a dictionary using join()
When joining a string with a dictionary, it will join with the keys of a Python dictionary, not with values.
Python3
dic = { 'Geek' : 1 , 'For' : 2 , 'Geeks' : 3 } # Joining special character with dictionary string = '_' .join(dic) print (string) |
Time Complexity: O(n)
Auxiliary Space: O(n)
Output:
'Geek_For_Geeks'
Please Login to comment...