Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find the nth occurrence of substring in a string in Python?
While working with strings, a common requirement is searching for a specific substring within a larger string. Python provides built-in methods that allow you to locate the first occurrence of a substring, but what if the substring appears multiple times and you need to find a specific occurrence?
For example, consider the string "Welcome to the Tutorialspoint to". If we look for the second occurrence of the substring "to", using the find() method will only return the first match. We need an approach that searches beyond the first occurrence, counting each one until we reach the nth.
In this article, we will explore different methods to find the nth occurrence of a substring in a string.
Using find() Method with Loop
The find() method returns the index of the first occurrence of a substring starting from a given position. We can use it repeatedly to find subsequent occurrences.
Syntax
str.find(value, start, end)
Example 1: Finding the Second Occurrence
Let's find the second occurrence of "to" in a string ?
def find_nth_occurrence(string, substring, n):
index = -1
for _ in range(n):
index = string.find(substring, index + 1)
if index == -1:
return -1
return index
text = "Welcome to the Tutorialspoint to"
result = find_nth_occurrence(text, "to", 2)
print(f"Second occurrence of 'to' is at index: {result}")
Second occurrence of 'to' is at index: 30
Example 2: Handling Non-existent Occurrences
When the nth occurrence doesn't exist, the function returns -1 ?
def find_nth_occurrence(string, substring, n):
index = -1
for _ in range(n):
index = string.find(substring, index + 1)
if index == -1:
return -1
return index
text = "TP Tutorialspoint"
result = find_nth_occurrence(text, 'p', 3)
print(f"Third occurrence of 'p': {result}")
Third occurrence of 'p': -1
Using split() Method
The split() method can split a string at a specified separator. By limiting the splits to n, we can calculate the position of the nth occurrence.
Syntax
str.split(separator, maxsplit)
Example
This approach splits the string and calculates the position based on the resulting parts ?
def find_nth_with_split(string, substring, n):
parts = string.split(substring, n)
if len(parts) <= n:
return -1
return len(string) - len(substring.join(parts[n:]))
text = 'Hi Hello Vanakam Hi'
substring = 'Hi'
result = find_nth_with_split(text, substring, 2)
print(f"Second occurrence of '{substring}' is at index: {result}")
Second occurrence of 'Hi' is at index: 17
Using Regular Expressions
Regular expressions provide another approach using the finditer() function ?
import re
def find_nth_with_regex(string, substring, n):
matches = list(re.finditer(re.escape(substring), string))
if len(matches) < n:
return -1
return matches[n-1].start()
text = "Welcome to the Tutorialspoint to learn"
result = find_nth_with_regex(text, "to", 2)
print(f"Second occurrence of 'to' is at index: {result}")
Second occurrence of 'to' is at index: 30
Comparison
| Method | Memory Usage | Performance | Best For |
|---|---|---|---|
find() with loop |
Low | Fast | Simple cases |
split() |
Higher | Moderate | When you need all parts |
| Regular expressions | Moderate | Slower | Complex patterns |
Conclusion
The find() method with a loop is the most efficient approach for finding the nth occurrence of a substring. Use split() when you need the separated parts, and regular expressions for complex pattern matching scenarios.
