The join() method in Python is used to concatenate the elements of an iterable (such as alist,tuple, orset) into a single string with a specified delimiter placed between each element.
Lets take a simple example tojoin list of string using join()method.
Joining a List of Strings
In below example, we usejoin() method to combine alist of strings into asingle stringwith each string separated by aspace.
Pythona=['Hello','world','from','Python']res=' '.join(a)print(res)
OutputHello world from Python
Syntax of join()
separator.join(iterable)
Parameters:
- separator:The string placed between elements of the iterable.
- iterable: A sequence of strings (e.g., list, tuple etc) to join together.
Return Value:
- Returns a single string formed by joining all elements in the iterable, separated by the specified separator
- If the iterable contains any non-string values and it raises aTypeError exception.
Examples of join() Method on Different Data Types
Below are examples of how join() method works with different data types.
Using join() with Tuples
Thejoin() method works with any iterable containing strings, includingtuples.
Pythons=("Learn","to","code")# Separator "-" is used to join stringsres="-".join(s)print(res)
Using join() with set
In this example, we are joining set of String.
Pythons={'Python','is','fun'}# Separator "-" is used to join stringsres='-'.join(s)print(res)
Note:Sincesets are unordered, the resulting string may appear in any order, such as "fun is Python" or "Python is fun".
Using join() with Dictionary
When using thejoin()method with adictionary, it will only join thekeys, not the values. This is becausejoin()operates on iterables of strings and the default iteration over a dictionary returns itskeys.
Pythond={'Geek':1,'for':2,'Geeks':3}# Separator "_" is used to join keys into a single stringres='_'.join(d)print(res)
Python String join() Method