![]() |
When we try to work in Python with the concepts of strings, this may create situations where you need to find out the second occurrence of a specific substring with a larger string. This may be achieved through out the different approaches as we know but we will try to explore Two different methods to do this. Find The Second Occurrence Of A Substring In Python StringBelow are some of the ways by which we can find the second occurrence of a substring in string in Python:
Find The Second Occurrence Of A Substring Using find() methodIn this example, the function `find_second_occurrence` is defined to find and return the index of the second occurrence of a specified substring in a given main string. The function checks for the first occurrence using `find()`, and if found, it looks for the second occurrence starting from the position after the first, providing the result or an error message if the substring appears only once or not at all. Python3
Output
Index of the second occurrence: 24 Time Complexity: O(n) Find The Second Occurrence Of A Substring Using
|
def find_second_occurrence_index_v2(main_str, sub_str): try : first_occurrence = main_str.index(sub_str) second_occurrence = main_str.index(sub_str, first_occurrence + 1 ) return second_occurrence except ValueError: return "Substring appears only once or not at all." # Example usage main_text = "Python is powerful, and Python is versatile." sub_text = "Python" result_index_v2 = find_second_occurrence_index_v2(main_text, sub_text) print ( "Index of the second occurrence:" , result_index_v2) |
Index of the second occurrence: 24
Time Complexity: O(n)
Space Complexity: O(1)
In this example, the function `find_second_occurrence_regex` utilizes the `re.finditer()` method to find all occurrences of the specified substring (`’Python’`) in a given main string. It then extracts the start positions of each match using a list comprehension. The example demonstrates finding the index of the second occurrence of the substring “Python” in the given main text using regular expressions.
import re def find_second_occurrence_regex(main_str, sub_str): matches = [match.start() for match in re.finditer(sub_str, main_str)] if len (matches) > 1 : return matches[ 1 ] else : return "Either the substring appears only once or not at all." # Example usage main_text = "Python is powerful, and Python is versatile." sub_text = "Python" result_regex = find_second_occurrence_regex(main_text, sub_text) print ( "Index of the second occurrence:" , result_regex) |
Index of the second occurrence: 24
Time Complexity: O(n)
Space Complexity: O(m)
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |