Python String partition
Now, we are going to learn about the partition method. Using this method, the string is split at the first occurrence of the specified separator. This method returns a 3 – tuple, containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, a 3 – tuple is returned, which contains the string itself, followed by two empty strings.
Let’s have a look at a simple program, which demonstrates the partition method.
Python String partition() Method
As you can see in the above program, we have a string, and then we are trying to call the partition method. We have specified the string ‘from’ as the separator. The partition method returns a 3 – tuple, which contains the part before the separator, the separator itself, and the part after the separator.
Let’s have a look at the output of the above program.
(‘Hello ‘, ‘from’, ‘ GyaniPandit’)
As you can see, we have got a 3 – tuple, which contains the part before the separator, then the separator itself, followed by the part after the separator. You can try the program for some other values as well.
Let’s say that we now give a separator, which is not there in the string, in such a situation, we are going to get a 3 – tuple, that contains the string, followed by two empty strings.
As you can see in the above program, we again have a string, and there we are trying to call the partition method. The separator that we are providing here, is not there in the string. So, we are going to get a 3 – tuple, which contains the string itself, followed by two empty strings.
So, as and when required, we can make use of the partition method in our python programs. Remember that here, we are going to give a separator, and the partition method is going to return a 3 – tuple, which contains the part before the separator, the separator itself, and the part after the separator. If the separator that we have specified is not found, then we get a 3 – tuple that contains the string itself, followed by two empty strings.