Python – Test if Substring occurs in specific position

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 >= 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)) 

chevron_right


Output :

The original string is : Gfg is best
Does string contain substring at required position ? : True

 

Method #2 : Using string slicing
This is one-liner way to perform this task. In this, we check the substring in string using string slicing.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output :

The original string is : Gfg is best
Does string contain substring at required position ? : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.