Python String join() Method
The join() method is used to combine elements of an iterable into a single string, placing a chosen separator between each element. It works only with iterables containing strings, making it an efficient way to build structured text.
Example 1: This example joins the elements of a tuple using a hyphen (-) as the separator, producing a structured string.
t = ("Learn", "Python", "Fast")
res = "-".join(t)
print(res)
Output
Learn-Python-Fast
Explanation: "-".join(t) inserts "-" between each tuple element to form a single string.
Syntax
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 combined string. Raises TypeError if any element is not a string.
Examples
Example 2: This example shows how join() handles a set. Since sets are unordered, the output order may vary each time.
s = {"Python", "is", "fun"}
res = " ".join(s)
print(res)
Output
fun is Python
Note: Since sets are unordered, the resulting string may appear in any order, such as "fun is Python" or "Python is fun", etc.
Example 3: Here, join() is applied to a dictionary. Since iteration over a dictionary defaults to keys, only the keys are joined.
d = {"Geek": 1, "for": 2, "Geeks": 3}
res = "_".join(d)
print(res)
Output
Geek_for_Geeks
Explanation: "_".join(d) joins dictionary keys because join() reads only the keys during iteration.