Python String endswith
Now, we are going to learn about the endswith method. As the name of the method suggests, with the endswith method, we are going to find whether or not, the given string ends with the specified string. This is like we are finding whether the string ‘GyaniPandit’ endswith ‘it’. The method is going to return True or False, on the basis of whether or not, the given string ends with the specified string. True is returned if the string endswith has given string, and False if not.
Let’s have a look at a simple program, which tries to demonstrate the same thing –
Python String endswith() Method
As you can see, we have a string, and we are checking whether the string endswith the specified string. This is very simple and easy to understand. The output in our case comes out to be True.
Now, Let’s say that we give such a string as an argument to the endswith method, such that the given string does not end with the specified argument. In such a case, the output is False. Let’s have a look at a simple program, which tries to demonstrate the same thing.
As you can see in the above program, we have a string, and then we are calling the endswith method. We are just checking whether or not, the given string endswith the string ‘bye’. The return value from the endswith method is going to be False. You can try executing the program and try to observe the output as well.
Also, we can give the optional start and end arguments, with which, we can specify a range to compare the string. This is like finding whether or not the string ends with some specified string but searching within the given range. Let’s have a look at a simple program, which tries to demonstrate the same thing.
As you can see in the above program, we have the simple string, and then we are trying to find if the string ends with the given argument, and also, we have specified the start and the end optional arguments, so that gives a range for comparison. The output for the above program comes out to be True. You can try to execute the program and observe the output as well. Also, you can simply play with the values as well.
So, as and when required, we can make use of the endswith method in our programs. Remember that with this method, we can check if the given string endswith some given argument. The method returns True or False, on the basis of whether or not, the string ends with the given string.