join() method in Python is used to combine elements of an iterable into a single string. It places the specified separator between each element. It is commonly used with lists and tuples, but it can work with any iterable whose elements are strings.
Example: Here the elements of a list are joined using a space as the separator.
words = ["Python", "is", "easy"]
result = " ".join(words)
print(result)
Output
Python is easy
Explanation:
- List contains three string elements.
- " ".join(words) places a space between each element.
- Resulting string is stored in result and printed.
Syntax
separator.join ( iterable )
Parameters:
- separator: Its the string placed between the elements.
- iterable: Contains the string needed to be joined.
Joining List
List of string can be joined using any required separator.
languages = ["Python", "Java", "C++"]
result = ", ".join(languages)
print(result)
Output
Python, Java, C++
Joining Tuple
join() also works with tuples containing strings.
items = ("Learn", "Python", "Fast")
result = " ".join(items)
print(result)
Output
Learn Python Fast
Joining Sets
They can also be passed to join(). However, sets are unordered, so the order of elements in the resulting string is not guaranteed.
items = {"Python", "Java", "C++"}
result = ", ".join(items)
print(result)
Output
C++, Java, Python
Joining Dictionary Keys
When a dictionary is passed directly to join(), Python iterates over its keys.
data = {
"Name": 1,
"Age": 2,
"City": 3
}
result = "-".join(data)
print(result)
Output
Name-Age-City
Joining a Generator
It can work with generators because generators are iterables.
words = (word for word in ["Python", "is", "fun"])
result = " ".join(words)
print(result)
Output
Python is fun
Using Empty Separator
An empty string can be used as the separator when no character should appear between elements.
words = ["Py", "thon"]
result = "".join(words)
print(result)
Output
Python