In this tutorial, we will learn how to join two strings in Python using the join()
method. Joining strings is a common operation in text processing and can be easily done using built-in functions in Python.
The join()
method is a string method that concatenates all the elements of an iterable (such as a list or a tuple) into a single string.
The method takes an iterable as its argument and returns a new string that is a concatenation of the elements present in the iterable. The string on which the method is called is used as a separator (delimiter) between the elements in the iterable.
Follow the steps below to join two strings using the join()
method in Python:
Step 1: Initialize the Strings
First, let’s initialize two strings that we want to join:
1 2 |
string1 = "Hello" string2 = "World" |
Step 2: Convert the Strings into a List or Tuple
In order to use the join()
method, we need to convert the two strings into an iterable such as a list or a tuple.
1 |
string_list = [string1, string2] |
Or, you can use a tuple:
1 |
string_tuple = (string1, string2) |
Step 3: Use the Join Method to Concatenate the Strings
Now, we can use the join()
method to concatenate the two strings. To do this, call the join()
method on the desired separator string and pass the list or tuple of strings as an argument.
For example, let’s use a space character as the separator:
1 2 |
separator = " " joined_string = separator.join(string_list) |
Or, using a tuple:
1 |
joined_string = separator.join(string_tuple) |
Step 4: Print the Result
Now, let’s print the result to see the output:
1 |
print(joined_string) |
Output:
Hello World
You can also use any other string as the separator, such as a comma, a hyphen, or an empty string.
Here’s the full code:
1 2 3 4 5 6 7 8 9 |
string1 = "Hello" string2 = "World" string_list = [string1, string2] separator = " " joined_string = separator.join(string_list) print(joined_string) |
Output:
Hello World
Conclusion
In this tutorial, we learned how to join two strings in Python using the join()
method. This method is very useful for concatenating strings with a specific separator, and can be easily extended to join more than two strings or other iterable elements. Remember that the join()
method requires an iterable as its argument, so make sure to convert your strings into a list or tuple before using the method.