Python String rfind() Method With Example

Python String rfind

Now, we are going to learn about the rfind method. With this method, we can get the highest index, where the given substring is found. If the substring is not found, then -1 is returned. Let’s have a look at a simple program, which demonstrates the same thing.

Python String rfind() Method

As you can see in the above program, we have the string, and then we are trying to call the rfind method. The rfind method is going to return the highest index of the given substring if the substring is found, and else it returns -1. In this case, the output from the method is 27, which is the highest index where the string is found.

Let’s consider a case now, in which we are going to give such a string as an input to the rfind method, which does not exist in the string. Let’s see the output in this case.

As you can see in the above program, we have a simple string, and then we are calling the rfind method, and we are passing a string as the input to the rfind method, which is not found in the given string. In such a case, we get the output as -1. You can try executing the program and observing the output.

We can also give some optional start and end indexes, specifying a range to search for. Let’s have a look at a simple example, which demonstrates the same thing.

As you can see in the above program, we have a simple string, and then we are calling the rfind method. We are passing the string, the start, and the end arguments to the method. So, the rfind method is going to return the highest index where the given substring is found in the given range. If you try to execute the program and observe the output from the program, it comes out to be 0.

So, as and when required, we can make use of the rfind method, to get the highest index of the given substring in the string, if found. If not found, the method returns -1.