Python string Method - join()

The join() method is a built-in Python string method that concatenates (joins) all the elements of an iterable (e.g., list, tuple, or set) into a string, using the calling string as a separator between each element.

Here's the syntax for the join() method:

separator.join(iterable)
Source:ww‮‬w.theitroad.com

Here, separator is the string that will be used as a separator between the elements of the iterable, and iterable is the iterable containing the elements to be joined.

Example:

# Example 1
fruits = ["apple", "banana", "cherry"]
separator = ", "
joined_fruits = separator.join(fruits)
print(joined_fruits)  # Output: "apple, banana, cherry"

# Example 2
numbers = [1, 2, 3, 4, 5]
separator = "-"
joined_numbers = separator.join(map(str, numbers))
print(joined_numbers)  # Output: "1-2-3-4-5"

In the above example, fruits is a list of strings, and we want to join them with a comma and space separator. In the first example, we use the join() method to concatenate the elements of the fruits list into a single string.

In the second example, we have a list of integers, and we want to join them with a dash separator. We first need to convert each integer to a string using the map() function and the str function, then use the join() method to concatenate them into a single string.