Python String join() Method
The join()
method is used to concatenate elements of an iterable (like a list, tuple, string, set, or dictionary) into a single string. The string on which the method is called acts as a separator between the elements.
Syntax
separator_string.join(iterable)
Parameters
iterable
: An iterable (like a list, tuple, string, or set) containing strings to be joined. All elements within the iterable must be strings, or a TypeError
will be raised.
Return Value
Returns a string created by joining the elements of the iterable with the string as the separator.
Examples
Joining a List of Strings
words = ["Python", "is", "amazing"]
sentence = " ".join(words)
print(sentence) # Output: "Python is amazing"
Joining With a Different Separator
You can use any string as a separator. Here is an example with a comma and a space.
fruits = ["apple", "banana", "mango", "watermelon"]
sentence = ", ".join(fruits)
print(sentence) # Output: "apple, banana, mango, watermelon"
Joining a Tuple of Strings
The join()
method works the same way with tuples
fruits = ("apple", "banana", "mango")
sentence = ", ".join(fruits)
print(sentence) # Output: "apple, banana, mango"
Joining a Dictionary Keys or Values
person = {"name": "James", "address": "Arizona"}
# Joining Keys
print(", ".join(person)) # Output: "name, address"
# Joining Values
print(", ".join(person.values())) # Output: "James, Arizona"
Joining With an Empty Separator
Using an empty string as a separator will concatenate elements with nothing in between.
fruits = ["Apple", "Banana", "Mango"]
sentence = "".join(fruits)
print(sentence) # Output: "AppleBananaMango"
Joining Non-String Elements
To join non-string elements, you need to convert them to strings first.
numbers = [5, 10, 15, 20]
str_numbers = ", ".join(str(num) for num in numbers)
print(str_numbers) # Output: "5, 10, 15, 20"