Write a Python program to find the index of a given string at which a given substring starts. If the substring is not found in the given string Not found


Python program that searches for the position (index) of a substring within a given string. The program checks if the substring pos is present within the string str1 and then prints the index where the substring is found.

  • It first checks if the length of pos is greater than the length of str1. If it is, it prints "Not found" because the substring cannot be longer than the string it's searching in.
  • If the lengths are compatible, the program initializes a Boolean variable found to False.
  • It then iterates through the characters of str1 using a for loop and checks if a substring of str1 starting at the current index and of the same length as pos matches pos.
  • If a match is found, it prints the index where the match starts and sets found to True. It then breaks out of the loop since the first occurrence of the substring has been found.
  • If no match is found after checking all positions, the program prints "Not found."

Source Code

str1 = "Python Exercises"
pos = "Ex"
 
if len(pos) > len(str1):
    print("Not found")
else:
    found = False
 
    for i in range(len(str1)):
        if str1[i:i+len(pos)] == pos:
            print("Index of the Substring = ",i)
            found = True
            break
 
    if not found:
        print("Not found")

Output

Index of the Substring =  7

Example Programs