Python String join() Method With Example

Python String join

Now, we are going to learn about the join method. Basically, the string join method returns a string joining all the elements from the provided iterable, separated by the specified separator. So, whenever we need to have a string, joining all the elements from some iterable, and separating the elements of the iterable with the specified separator, we can make use of the join method.

Now, Let’s have a look at a simple program, which tries to demonstrate the same thing here.

Python String join() Method

As you can see in the above program, we have a list, as an iterable, which has some strings, and then we are calling the join method, on a string, which is basically a separator. Here, the separator is ‘#’. The join method returns a string, joining all the elements from the iterable, separated with the given separator. So, when we are printing the string1 in our program, we get the output something like this –

Hello#from#GyaniPandit

As you can see, we got a string, which joins all the elements from the iterable, which are separated by the given separator. In this case, the separator is ‘#’. Notice that we need to have the separator, and in the iterable as well, if the element is not a string, then it raises TypeError. Let’s have a look at a simple program, which demonstrates the same thing.

As you can see that in the above program, we have the list again, but this time, in the list, we have a non-string element in the list, so we are going to get a TypeError. You can try executing the program and observing the output as well.

To the join method, we can pass some iterable as an argument, which means that we can provide some list, tuple, string, dictionary, or set as well. The thing is that if you are passing the dictionary as an iterable, then also, the keys would be tried to join, and not the values. So, if the key is not a string, then also we are going to get into the TypeError. You can try having the dictionary as an argument to the join method.

As and when required, we can make use of the join method in our Python programs. Remember that with the join method, we get a string, which joins all the elements from the given iterable, and the string is separated with the given separator.