w3resource

Python: Find the index of a given string at which a given substring starts


Index of substring or "Not found".

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

Sample Solution:

Python Code:

# Function to find index of substring
def find_Index(str1, pos):
  # Check if pos longer than str1
  if len(pos) > len(str1):
    return 'Not found'
  # Iterate through str1
  for i in range(len(str1)):
    # Iterate through pos
    for j in range(len(pos)):
      # If match found, return index
      if str1[i + j] == pos[j] and j == len(pos) - 1:
        return i
      # Break if mismatch
      elif str1[i + j] != pos[j]:
        break
  return 'Not found'
# Test cases
print(find_Index("Python Exercises", "Ex"))
print(find_Index("Python Exercises", "yt"))
print(find_Index("Python Exercises", "PY"))

Sample Output:

7
1
Not found

Flowchart:

Flowchart: Find the index of a given string at which a given substring starts.

For more Practice: Solve these Related Problems:

  • Write a Python program to find the starting index of a given substring in a string and return "Not found" if it doesn't exist.
  • Write a Python program to use the find() method to locate a substring and handle negative return values appropriately.
  • Write a Python program to implement a function that searches for a substring and returns its index using a loop.
  • Write a Python program to use regular expressions to determine the position of a substring and output a default message if absent.

Go to:


Previous: Write a Python program to count number of substrings with same first and last characters of a given string.
Next: Write a Python program to wrap a given string into a paragraph of given width.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.