Python provides various string methods to perform operations on strings. One of them is the join()
method. The join()
method is used to join a sequence of strings into a new string, using a specified delimiter between each string.
Syntax
The syntax for using the join()
method is as follows:
delimiter.join(sequence)
Here, delimiter
is the string that separates the strings in the sequence
parameter.
Return Value
The join()
method returns a new string that is the concatenation of the strings in the sequence
parameter, separated by the delimiter
string.
Examples
Here are some examples to illustrate the usage of the join()
method:
Example 1: Joining a List of Strings with a Delimiter
fruits = ["apple", "banana", "cherry"] delimiter = ", " joined_fruits = delimiter.join(fruits) print(joined_fruits)
Output:
apple, banana, cherry
In this example, the join()
method is used to join the elements of the fruits
list with a comma and a space delimiter. The resulting string is assigned to the joined_fruits
variable and printed.
Example 2: Joining a Tuple of Strings with a Delimiter
cars = ("Ford", "BMW", "Volvo") delimiter = " and " joined_cars = delimiter.join(cars) print(joined_cars)
Output:
Ford and BMW and Volvo
In this example, the join()
method is used to join the elements of the cars
tuple with an “and” delimiter. The resulting string is assigned to the joined_cars
variable and printed.
Example 3: Joining a Set of Strings with a Delimiter
colors = {"red", "green", "blue"} delimiter = "-" joined_colors = delimiter.join(colors) print(joined_colors)
Output:
green-blue-red
In this example, the join()
method is used to join the elements of the colors
set with a hyphen delimiter. The resulting string is assigned to the joined_colors
variable and printed.
Use Cases
The join()
method can be used in various situations where strings need to be concatenated with a specific delimiter. Some common use cases include:
- Joining words to form a sentence
- Joining file paths in a directory structure
- Joining database queries with a separator
Overall, the join()
method is a useful tool for combining strings into a single string with a specified separator.