Python String find
Now, we are going to learn about the find method. As the name of the method suggests, this method is going to return the first occurrence index of the string in the given string, if it is present, and if the string is not present, then we get -1 as the return value.
Have a look at the below program now –
Python String find() Method
As you can see, we have a string, and we are trying to find the first occurrence index of the string ‘pandit’ in the string ‘Gyanipandit’. The output that we are going to get in this case, is the index 5 because that is where the string ‘pandit’ starts in the string ‘Gyanipandit’. If we try to find some string that is not there in the given string, then we are going to get -1 as an output.
Have a look at the below program as well, which tries to demonstrate the same thing.
As you can see, in the above program now, we are trying to find the string ‘python’, in the string ‘Gyanipandit’, and in this case, we are going to get -1 as our output, since the string ‘python’ is not present there in the string ‘Gyanipandit’.
Also, we can provide some more additional arguments to the find method, like the start and end. By giving this, we are giving a range, in which we want to find the first occurrence of the string in the given string.
As you can see in the above program, we have a simple string, and then we are trying to find the first occurrence of the string ‘el’ in the given string. Also, this time, we are giving the start and end arguments. Within the specified start and end, we are trying to search for the first occurrence index of the specified string.
So, as and when required, we can make use of the find method, to find the first occurrence index of some string inside the given string.