Python String find: How to Find First Occurrence of SubString
Python String find() is an inbuilt function that returns the index of the first occurrence of the substring (if found). If not found, it returns -1.
If the start and end indexes are not provided then by default, it takes 0 and length -1 as starting and ending indexes where the ending indexes are not included in our search.
Python String find()
Python string find() function is almost the same as the Python string index() method, and the only difference is that the index() method raises an exception if the value is not found. Python find() method is used to find the index of a substring in the string.
The syntax for the find() method is the following.
string.find(value, start, end)
The value parameter is required, and it is the value we are searching for.
The start parameter is optional, and it is where to start searching for.
The end parameter is optional, and it is where to end the search.
The find() method returns an integer value. If substring exists inside the string, it returns the index of the first occurrence of the substring. If the substring doesn’t exist inside the string, it returns -1.
Let’s see the following example.
# app.py line = 'Every Marvel Movies are great movies' index = line.find('Marvel') print(index)
Here, the string index starts from 0. So the Marvel substring is starting from 6th. See the output.
Find Letter between positions
Let’s find the first letter occurrence between the specified positions.
# app.py line = 'Every Marvel Movies are great movies' index = line.find('e', 6, 20) print(index)
In the above example, we will start searching for a letter e from position 6 and ending at 20.
See the output.
Let’s see another example where we don’t find the character in the String.
# app.py line = 'Every Marvel Movies are great movies' index = line.find('k') print(index)
The above example will return the -1 as we do not find any character k in the string.
So, using the Python String find() method, we can search for substring as well as character, and if it is there then we will get its index as a return value.
Finally, Python String find() method example tutorial is over.