In this Tutorial, we will learn How To Find All Occurrences Of A Substring from a String? In Python, we can find All Occurrences Of A Substring by using some inbuild functions which are string.rfind(), String.find(), and String.find_all().
Different Ways To Finding Occurrences Of A Substring
There are a number of ways to find the occurrences of a substring in a String where we can get the exact indexes of the location. Provided the output will be showing the starting index of the substring from where it starts matching.
Here we can say that all the in-build functions return the index number of the first character from where the substring starts occurring in the main String So let’s make it more clear with the examples of all one by one.
tring = "test test test test" print string.find('test') # 0 print string.rfind('test') # 15 #this is the goal print string.find_all('test') # [0,5,10,15]
Let’s start with the first which is
string.find()
It is used for a single occurrence so it returns the single value where the substring occurs for the first time and it will not check for the next so the index that this function return might be missing the rest of the missing indexes. As in the above code, we can see that it is returning Zero as the index number of the first occurrence of the substring is 0 Only.
string.rfind()
It is also a build function that helps in finding the occurrence of a substring in the given entire String, But it returns the index number where the substring occurred for the last time means if there is more than one time the substring is occurring then it will result from the index number where it has occurred last.
As we can easily understand from the above code where the function is returning 15 as at the index 15 it is the last time where the substring is occurring.
string.find_all()
As we have seen above examples of different ways to get the indexes of occurrences of a substring from a main String It is the way to get all the indexes where the substring is matching or occurring in the String.
As we can see in the above code that string.find_all() is giving the result as all the indexes from where the substring is occurring.
Learn more about How to find all occurrences of a substring?: https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring
And we can also learn more at: Some Basic Python String and substring Programs