Python string join() Method

In this tutorial, We will see the python string join() method with examples.

join() Method

The join() method is one of the methods in a python string. The python string join() method is used to join or combine strings into one string.

Syntax of Python string join() method
separator.join(iterable)
  • The join() method, joins separator to the element of iterable object except last.
  • String, dictionary, tuple, set, list all are iterable objects.
  • The join() method can be used if the iterable object has string values.
  • If the iterable object has a non-string value, using the join() method will result in an error.
Example: join() Method with string
s = "python" #string 

''' "-" is a separator and s is an iterable object(string). '''

'''joins "-" to each element of string except last. '''

print("-".join(s)) 

#Output: p-y-t-h-o-n
Example: join() Method with list
list = ["Python","Data Science","Machine Learning"] #strings inside the list

separator = "#" 

''' "#" is a separator and a variable list is an iterable object(list).'''

''' joins "#" to each element of the list except last.'''

print(separator.join(list))

#Output: Python#Data Science#Machine Learning
Example: join() Method with tuple
#strings inside the tuple

tuple = ("America","japan" ,"India") 

separator = "--" 

''' "--" is a separator and a variable tuple is an iterable object(tuple). '''

''' joins "--" to each element of the tuple except last. '''

print(separator.join(tuple))

#Output: America--japan--India
Example: join() Method with Dictionary
#Dictionary Keys

#country with calling code

dictionary = {"Japan":"+81","America":"+1","Russia":"+7","India":"+91"}

separator = "**" 

''' "**" is a separator and a variable dictionary is an iterable object(dictionary).'''

''' joins "**" to each key of the Dictionary except last.'''

print(separator.join(dictionary))

#Output: Japan**America**Russia**India
#Dictionary values

#country with calling code

dictionary = {"Japan":"+81","America":"+1","Russia":"+7","India":"+91"}

separator = "**" 

''' "**" is a separator and a variable dictionary is an iterable object(dictionary).'''

value = dictionary.values()

''' joins "**" to each value of the Dictionary except last.'''

print(separator.join(value))

#Output: +81**+1**+7**+91
Example: join() Method with set
# strings inside set

set = {"Japan","America","Russia","India"}

separator = "%" 

''' "%" is a separator and a variable set is an iterable object(set). '''

''' joins "%%" to each element of set except last. '''

print(separator.join(set))

#Output: Russia%Japan%India%America

Related Posts