Find the Second Occurrence of a Substring in Python String
In this article, we will discuss different methods (find, split and regular expression module) to find the second occurrence of a substring in a given string.
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second occurrence of a word in a sentence, or a phrase in a paragraph.
In this article, we will discuss the different way to perform this operation on strings. We will be covering the following sections today:
- Different Methods to Find the Second Occurrence of a Substring in Python String
So, without further ado, let us get started!
Different Methods to Find the Second Occurrence of a Substring in Python
Use find() method
Here’s the syntax for this predefined string find function in Python:
.find(value, start, end)
Let’s talk about the three arguments passed to the function as you can see in the syntax above:
- Value: (Mandatory) This argument specifies the value to search for.
- Start: (Optional) This argument specifies the position to start the search. The default is 0.
- Start: (Optional) This argument specifies the position where the search would end. The default is the end of the string.
Let’s see how we can use this function too find the second occurrence of a substring in a given string:
def find_string(txt, str1): return txt.find(str1, txt.find(str1)+1) string = input("Enter the string: ")substring = input("Enter the substring: ")
print("The index of the second occurence of the substring: ", find_string(string, substring))
Output 1:
How did we get the value 9? Here’s how:
The second occurrence of the substring “the” starts at the index 9, as you can see above.
Let’s look at one more example:
Output 2:
Why did we get the value 17? Because the string find() function is case-sensitive:
Must Check: Python Online Course & Certification
Use split() method
Another way is to split the given string at the substring. Here’s the syntax for this predefined string split function in Python:
.split(separator, maxsplit)
Let’s talk about the two arguments passed to the function as you can see in the syntax above:
- Separator: (Optional) This argument specifies the substring by which the original string has to be split. The default is the whitespace.
- Maxsplit: (Optional) This argument provides the maximum number of splits the original string should go through. In this case, the maximum splits would be n + 1, where n is the number of occurrences. Since we need to find the second occurrence – n = 1 (the first occurrence is given by n=0).
The split() function returns a list object that contains the split substrings which can be accessed by traversing the list.
We will find the index of the second substring by using a simple formula –
(length of input string – length of the last split part – length of the substring)
def find_substring(txt, str1, n): parts = txt.split(str1, n + 1) if len(parts) <= n + 1: return -1 return len(txt) - len(parts[-1]) - len(str1)
string = input("Enter the string: ")substring = input("Enter the substring: ")occur = 1 #first occurence is given by 0 and second occurence is given by 1
print("The index of the second occurence of the substring: ", find_substring(string, substring, occur))
Output:
Use Python Regular Expression Module
One more way to find the second occurrence of a substring is use the re module in Python. Let’s see how this is used:
#import regex libraryimport re
string = input("Enter the string: ")substring = input("Enter the substring: ")occur = 2
#Finding the nth occurrence of substringinilist = [i.start() for i in re.finditer(substring, string)]if len(inilist)>= occur: #Printing result print("The index of the second occurence of the substring: ", inilist[occur-1])else: print ("No {} occurrence of substring lies in given string".format(occur))
Output 1:
Let’s look at one more example:
Output 2:
As you can see from the code above, we use the re.finditer() method to find the occurrence of a particular pattern in a string. It takes two arguments – a pattern (in this case, it refers to our substring) and a string.
Best-suited Python courses for you
Learn Python with these high-rated online courses
Conclusion
Hope this article was helpful for you to understand how to use the find(), split() and re.finditer() methods to find the second occurrence of a substring in a Python string. Want to learn more about Python and practice Python programming? Explore related articles here.
Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio