Open In App

Python – Test if Substring occurs in specific position

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using loop
 
# initializing string
test_str = "Gfg is best"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing range
i, j = 7, 11
 
# initializing substr
substr = "best"
 
# Test if Substring occurs in specific position
# Using loop
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
 
# printing result
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




# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using string slicing
 
# initializing string
test_str = "Gfg is best"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing range
i, j = 7, 11
 
# initializing substr
substr = "best"
 
# Test if Substring occurs in specific position
# Using string slicing
res = test_str[i: j] == substr
 
# printing result
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




# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
 
# initializing string
test_str = "Gfg is best"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing range
i, j = 7, 11
 
# initializing substr
substr = "best"
 
# Test if Substring occurs in specific position
# Using string slicing
res = False
if(test_str.find(substr) == i):
    res = True
# printing result
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:

  1. 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.
  2. 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.
  3. 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




# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
 
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)
 
 
# initializing string
test_str = "Gfg is best"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing range
i, j = 7, 11
 
# initializing substr
substr = "best"
 
result = substring_occurs_at_position(test_str, substr, i, j)
# printing result
print("Does string contain substring at required position? ", result)
#this code contributed by tvsk


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
 
# initializing string
test_str = "Gfg is best"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing range
i, j = 7, 11
 
# initializing substr
substr = "best"
 
# Test if Substring occurs in specific position
# Using regular expression
pattern = "^" + substr + "$"
res = bool(re.search(pattern, test_str[i:j+1]))
 
# printing result
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 can be performed. Method #1: Using list comprehensio
7 min read
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 can be performed. Method #1: Using list comprehensio
5 min read
Python - Test if K occurs N consecutive times
Sometimes, while working with Python list, we can have a problem in which we need to check if a particular number occurs N consecutive times. This can have application in many domains including day-day programming. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is a way in which this task c
10 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 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 performed in Python. Ways to Insert Character Into Stri
6 min read
PyQtGraph – Getting Points Object at Specific Position in Scatter Plot Graph
In this article, we will see how we can get the point object at a specific location of the plot graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying d
3 min read
Select specific column of PySpark dataframe with its position
In this article, we will discuss how to select a specific column by using its position from a pyspark dataframe in Python. For this, we will use dataframe.columns() method inside dataframe.select() method. Syntax: dataframe.select(dataframe.columns[column_number]).show() where, dataframe is the dataframe namedataframe.columns[]: is the method which
2 min read
Insert a given column at a specific position in a Pandas DataFrame
In this comprehensive guide, we will leverage the powerful DataFrame.insert() the method provided by the Pandas library to effectively Insert a given column at a specific position in a Pandas Dataframe. Create a Sample DataFrame In this example below code uses Pandas to create a DataFrame named 'df' from a dictionary with columns 'col2' and 'col3'
4 min read
Python | Check if k occurs atleast n times in a list
There are many common problems that a developer or common programmer comes across in day-day coding. One such problem is finding if an element occurs more than a certain number of times in the list. Let's discuss certain ways to deal with this problem. Method #1 : Using sum() + list comprehension The list comprehension can be clubbed with the sum f
8 min read
Python program to check if given value occurs atleast k times
Given a list and some value (let's say it N), write a Python program to check if the given value occurs atleast k-times in that list. We can use list comprehension to deal with this problem. We can add each occurrence of given value and check if it is greater than or equal to k. If the value returned is True, then set the flag to 1, else 0. Below i
4 min read
Practice Tags :
three90RightbarBannerImg