Why do we use the join() function in Python?
The join() method joins all the items of a list, tuple or other iterable into one string. The string you call it on is used as the separator between the items.
words = ["Learn", "Python", "Fast"]
print(" ".join(words))
print("-".join(words))
print("".join(words))
Output:
Tutorials Class - Output Window
Learn Python Fast
Learn-Python-Fast
LearnPythonFast
All items must be strings. If the list has numbers, you get a TypeError, so convert them first.
numbers = [1, 2, 3]
print(",".join(str(n) for n in numbers))
Output:
Tutorials Class - Output Window
1,2,3
join() is also faster than adding many strings with + in a loop.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |