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 |
|---|
| Python Strings |
| Exercises & Assignments |
|---|
| Python program to check palindrome string |
| Python program to count vowels in a string |
| Python program to reverse a string |
| Interview Questions & Answers |
|---|
| How would you convert a string into lowercase? |
| How would you convert a string into uppercase? |
| Why do we use the join() function in Python? |
| What are f-strings in Python? |