In python, the string find() method is useful to search the string for specified substring and return the index position of the first occurrence of the specified substring. In case if the specified substring/character is not found, it will return -1
.
Following is the pictorial representation of a string find()
method functionality in python.
If you observe the above diagram, we are trying to find the "Hi
" word in the given string “Hi Guest Hi
” using the find
function in python and it returned the index position of the first occurred specified substring as 0
. In python, the index position will always start from 0
, so it returned the index position 0
.
Following is the syntax of defining a string find method in python.
If you observe the above syntax, the find()
method accepts three parameters (string/char
, startIndex
, endIndex
). Here, startIndex
and endIndex
parameters are optional.
0
.Following is the example of searching the specified substring/character in the given string using the string find() method in python.
If you observe the above example, we are searching the required substrings in the given string using find()
method without specifying start
/end
index parameters.
When you execute the above python program, you will get the result as shown below.
As discussed in the earlier chapters, python is a case sensitive language due to that the substring 'hi
' was found at index position 9
even though the string starts with 'Hi
'. For another substring 'Tutlane
', it returned -1
because the specified substring was not found with the same case.
We didn’t mention any start/end
index positions to search for the specified substrings in the above example. By default, the string find()
method will search the complete string for the specified substrings/characters.
If you want to limit the search range, you need to mention the start
and end
index parameter values in the find()
method.
Following is the example of searching the substrings/characters within the specified index positions range using the find()
method.
If you observe the above example, we are limiting the string search by specifying the start
and end
index positions in find() method.
When you execute the above python program, you will get the result as shown below.
This is how you can use the string find() method in python to search for the specified substring/character in the given string based on your requirements.