Open In App

Find the Index of a Substring in Python

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.

Using str.find()

The find() method searches for the first occurrence of the specified substring and returns its starting index. If the substring is not found, it returns -1.

python-substring-indexof
Using find() to check the index of a substring

Example:

Python
s = "GeeksforGeeks"

# Define the substring we want to find
s1 = "eeks"

# Use the find() method to locate the starting index of the substring 's1' in the string 's'
index = s.find(s1)
#Print either satarting position of 's1' or -1 if not found
print(index)

Output
1

Using str.index()

The index() method is similar to find() but raises a ValueError if the substring is not found. This method requires error handling if the substring is not present.

Python
s = "GeeksforGeeks"

# Define the substring we want to find
s1 = "or"

try:
  #index() returns the starting position of 's1' in 's'
    index = s.index(s1)
    print(f"The substring '{s1}' is found at index {index}.")
except ValueError:
  ## If the substring is not found, the index() method raises a ValueError
    print(f"The substring '{s1}' is not present in the text.")

Output
The substring 'or' is found at index 6.

Using str.split()

This approach works well for word-based matches. Splitting the string and finding the substring's index in the resulting list can be useful for finding whole words.

Python
s = "Geeks for Geeks"

# Define the substring we want to find
s1 = "for"

parts = s.split(s1)

# Check if the substring is in the string
if len(parts) > 1:
    # Calculate the starting index of the substring
    index = len(parts[0]) 
    print(f"The substring '{s1}' is found at index {index}.")
else:
    print(f"The substring '{s1}' is not present in the text.")

Output
The substring 'for' is found at index 6.

Using re.search()

The re.search() in Python's re module can be used to locate the first occurrence of a pattern in a string. While re.search() itself doesn’t directly return the starting or ending index of the match with this you can extract this information using the Match object's start() and end() methods.

Python
import re

s = "hello world"
s1 = "ello"

# Use the re.search() function to search for the substring in the main string
match = re.search(s1, s)
if match:
  # If a match exists, print the starting index of the substring
    print(f"The substring '{s1}' is found at index {match.start()}")
else:
  # If no match is found, print that the substring is not present
    print(f"The substring '{s1}' is not present in the text")

Output
The substring 'ello' is found at index 1

Next Article
Practice Tags :

Similar Reads