Open In App

How to Get Index of a Substring in Python?

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

To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Let’s explore how to efficiently get the index of a substring.

The simplest way to get the index of a substring in a string is by using the find() method. This method returns the first index where the substring is found or -1 if the substring does not exist.

Python
s1 = "Welcome to Python programming"
s2 = "Python"

# Using find() method
sub = s1.find(s2)
print(sub)

Output:

11

find() method searches for the substring "Python" in the string and returns the index of its first occurrence. If the substring is not found, it returns -1.

Let's Explore other methods of finding index of a substring in python:

Using str.index()

Another way to find the index of a substring is by using the index() method. Unlike find(), it raises a ValueError if the substring is not found, making it useful for cases where you want to ensure the substring exists.

Python
# Using index() method
s1 = "Welcome to Python programming"
s2 = "Python"

# using try..except to handle exception, 
# in case substring is not found
try:
    sub = s1.index(s2)
    print(sub)
    
except ValueError:
    print("Substring not found")

Output
11

index() method returns index of first occurrence of the substring "Python". If the substring is not present, it raises a ValueError.

Using Regular Expressions

For more complex matching scenarios, you can use regular expressions with the re module. This allows for pattern-based searches within strings.

Python
import re

s1 = "Welcome to Python programming"
s2 = "Python"

# Using regex to find the substring
match = re.search(s2, s1)
if match:
    print("Found at index:", match.start())
else:
    print("Substring not found")

Output
Found at index: 11

re.search() method searches for the first occurrence of the pattern and returns a match object. The match.start() method returns the starting index of the match.



Next Article

Similar Reads