The join()
method in Python is used to concatenate a sequence of strings from an iterable (e.g., a list, tuple, or set) into a single string, with each element separated by the string on which the join()
method is called.Here's the syntax of the join()
method:
separator_string.join(iterable)
separator_string
: The string that will be used as a separator between the elements in the resulting string.iterable
: An iterable (e.g., a list, tuple, set) containing strings that will be joined together.
# Example using join() method
words = ["Hello", "world", "Python"]
separator = " "
result = separator.join(words)
print("Words:", words)
print("Result after join:", result)
Words: ['Hello', 'world', 'Python']
Result after join: Hello world Python
In this example, we have a list of strings called words
containing three elements: "Hello", "world", and "Python". We want to join these elements into a single string with spaces as separators, so we use the join()
method with a space " "
as the separator. The resulting string is "Hello world Python".
The join()
method is commonly used to concatenate strings efficiently. It is particularly useful when you have a collection of strings that you want to join together with a specific separator to form a longer string.