Find the Second Occurrence of a Substring in Python String

Find the Second Occurrence of a Substring in Python String

3 mins read19.5K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Aug 16, 2024 15:28 IST

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.

2022_08_second-occurence.jpg

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:

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))
Copy code

Output 1:

2022_07_image-153.jpg

How did we get the value 9? Here’s how:

2022_07_image-154.jpg

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:

2022_07_image-155.jpg

Why did we get the value 17? Because the string find() function is case-sensitive:

2022_07_image-156.jpg

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))
Copy code

Output:

2022_07_image-157.jpg

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 library
import re
string = input("Enter the string: ")
substring = input("Enter the substring: ")
occur = 2
#Finding the nth occurrence of substring
inilist = [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))
Copy code

Output 1:

2022_07_image-158.jpg

Let’s look at one more example:

Output 2:

2022_07_image-159.jpg

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.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

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.

Understanding Substring Function in C++
Understanding Substring Function in C++
A substring in C++ is a portion of a string that can be extracted using the substr() function. The substring function in C++ allows you to extract a specific segment...read more
About the Author
author-image
Vikram Singh
Assistant Manager - Content

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