Python – Test if Substring occurs in specific position
Last Updated :
08 Apr, 2023
Sometimes, while working with python strings, we can have a problem in which we need to test occurrence of substring. There is straight forward way to test this. But sometimes, we have a more specific problem in which we need to test if substring occurs at that particular position. Let’s discuss certain ways in which this task can be performed.
Method #1: Using loop This is brute method to solve this problem. In this we iterate the string and when index occur we test for substring characters simultaneously.
Python3
test_str = "Gfg is best"
print ( "The original string is : " + test_str)
i, j = 7 , 11
substr = "best"
res = True
k = 0
for idx in range ( len (test_str)):
if idx > = i and idx < j:
if test_str[idx] ! = substr[k]:
res = False
break
k = k + 1
print ( "Does string contain substring at required position ? : " + str (res))
|
Output :
The original string is : Gfg is best
Does string contain substring at required position ? : True
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is needed
Method #2: Using string slicing This is a one-liner way to perform this task. In this, we check the substring in string using string slicing.
Python3
test_str = "Gfg is best"
print ( "The original string is : " + test_str)
i, j = 7 , 11
substr = "best"
res = test_str[i: j] = = substr
print ( "Does string contain substring at required position ? : " + str (res))
|
Output :
The original string is : Gfg is best
Does string contain substring at required position ? : True
Method #3 : Using find() method
Python3
test_str = "Gfg is best"
print ( "The original string is : " + test_str)
i, j = 7 , 11
substr = "best"
res = False
if (test_str.find(substr) = = i):
res = True
print ( "Does string contain substring at required position ? : " + str (res))
|
Output
The original string is : Gfg is best
Does string contain substring at required position ? : True
Method#4: Using Recursive method.
Algorithm:
- Check if the ending index j is greater than the length of the input string test_str. If it is, return False, because the substring cannot exist outside the range of the input string.
- Check if the substring starting from index i and ending at index j is equal to the input substring substr. If it is, return True, because the substring has been found at the specified position.
- Otherwise, call the function recursively with the starting index incremented by 1 and the ending index incremented by 1, to check the next possible substring.
Python3
def substring_occurs_at_position(test_str, substr, i, j):
if j > len (test_str):
return False
if test_str[i:j] = = substr:
return True
return substring_occurs_at_position(test_str, substr, i + 1 , j + 1 )
test_str = "Gfg is best"
print ( "The original string is : " + test_str)
i, j = 7 , 11
substr = "best"
result = substring_occurs_at_position(test_str, substr, i, j)
print ( "Does string contain substring at required position? " , result)
|
Output
The original string is : Gfg is best
Does string contain substring at required position? True
The time complexity of this function is O(n), where n is the length of the input string test_str. This is because in the worst case, the function will need to iterate over the entire string to find the substring.
The auxiliary space complexity of the function is O(1), because it does not use any extra space that is proportional to the size of the input. The function only uses a constant amount of space to store the input parameters and temporary variables.
Method #5: Using Regular Expression
Step-by-step approach:
- Import the re module.
- Define a regular expression pattern that matches the substring at the specific position in the string. The pattern should use the “^” character to anchor the search at the specific position and the “$” character to match the end of the string.
- Use the re.search() function to search for the regular expression pattern in the string.
- If a match is found, set the result to True, else set it to False.
- Print the result.
Python3
import re
test_str = "Gfg is best"
print ( "The original string is : " + test_str)
i, j = 7 , 11
substr = "best"
pattern = "^" + substr + "$"
res = bool (re.search(pattern, test_str[i:j + 1 ]))
print ( "Does string contain substring at required position ? : " + str (res))
|
Output
The original string is : Gfg is best
Does string contain substring at required position ? : True
The time complexity of this program is O(1) because it uses a constant amount of time to compile the regular expression pattern and search for the pattern in the string.
The auxiliary space of this program is also O(1) because it uses a constant amount of memory to store the regular expression pattern and the result of the search operation.
Similar Reads
Python | Filter String with substring at specific position
Sometimes, while working with Python string lists, we can have a problem in which we need to extract only those lists that have a specific substring at a specific position. This kind of problem can come in data processing and web development domains. Let us discuss certain ways in which this task ca
5 min read
Add Substring at Specific Index Python
In Python, String is an immutable datatype, what this means is, that there are lot many restrictions when one handles its manipulation. The problem of adding something at a position at string is not possible, without the list reconstruction. Let's discuss certain ways in which this task can be perfo
6 min read
Python - All occurrences of substring in string
A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String. Using re.finditer()re.finditer() returns an iterator yielding match object
3 min read
Get Second Occurrence of Substring in Python String
We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
2 min read
Python | Get the string after occurrence of given substring
The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python. Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read
Python - All occurrences of Substring from the list of strings
Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is reco
5 min read
Python program to find the occurrence of substring in the string
Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
4 min read
Python | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.findite
4 min read
Find the List elements starting with specific letter - Python
The goal is to filter the elements of a list that start with a specific letter, such as 'P'. For example, in the list ['Python', 'Java', 'C++', 'PHP'], we aim to find the elements that begin with the letter 'P', resulting in the filtered list ['Python', 'PHP']. Let's explore different approaches to
3 min read
Python | Find last occurrence of substring
Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can fin
8 min read