Python join() Function
The join() function in Python is used when we need to join all the items of an iterable into a string. For example:
mylist = ["01", "Dec", "2021"] str = "-" res = str.join(mylist) print(res)
The output will be:
Python join() Function Syntax
The syntax of join() function in Python, is:
where str refers to the string and iterable refers to an iterable object. When dictionary is used as an iterable, their keys will get used.
Note: The str acts as a separator among all the joined items of specified iterable.
Python join() Function Example
Here is an example of String.join() function in Python:
a = ["We", "love", "codescracker"] b = ("Python", "is", "fun") c = {"Date": "01", "Month": "Dec", "Year": "2021"} d = {"01": "Date", "12": "Month", "2021": "Year"} e = {"Dec", "2021"} m = " ".join(a) n = " ".join(b) o = "/".join(c) p = "/".join(d) q = ", ".join(e) print(m) print(n) print(o) print(p) print(q)
The snapshot given below shows the sample output produced by above program, demonstrating the join() function in Python:
Of course the above program can also be created in this way too:
print(" ".join(["We", "love", "codescracker"])) print(" ".join(("Python", "is", "fun"))) print("/".join({"Date": "01", "Month": "Dec", "Year": "2021"})) print("/".join({"01": "Date", "12": "Month", "2021": "Year"})) print(", ".join({"Dec", "2021"}))
« Previous Function Next Function »
Liked this post? Share it!