The Wayback Machine - https://web.archive.org/web/20240910181459/https://www.geeksforgeeks.org/find-the-index-of-a-substring-in-python/
Open In App

Find the Index of a Substring in Python

Last Updated : 15 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Working with strings is a common task in Python programming, and finding the index of a substring within a string is a frequent requirement. Whether you’re dealing with text processing, data analysis, or any other application, having the ability to locate a substring efficiently is crucial. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.

Find The Index Of A Substring In Python

Below, are the methods to Find The Index Of A Substring In Python.

Find The Index Of A Substring Using find() Function

In this example, the below code finds the index of the substring “world” within the string “Hello, world!” using the `find()` method. If the substring is found (index is not -1), it prints the index; otherwise, it indicates that the substring is not present in the text.

Python3




text = "Hello, world!"
substring = "world"
 
index = text.find(substring)
 
if index != -1:
    print(f"The substring '{substring}' is found at index {index}.")
else:
    print(f"The substring '{substring}' is not present in the text.")


Output

The substring 'world' is found at index 7.


Find The Index Of A Substring Using index() Function

In this example, below code attempts to find the index of the substring “programming” within the string “Python programming” using the `index()` method. If the substring is found, it prints the index; otherwise, it catches the `ValueError` exception .

Python3




text = "Python programming"
substring = "programming"
 
try:
    index = text.index(substring)
    print(f"The substring '{substring}' is found at index {index}.")
except ValueError:
    print(f"The substring '{substring}' is not present in the text.")


Output

The substring 'programming' is found at index 7.


Find The Index Of A Substring Using split() Function

In this example, below code finds the index of the word “Science” in the string “Data Science is fascinating” by first splitting the string into words. It prints the index if the word is found, or a message if it’s not present.

Python3




text = "Data Science is fascinating"
substring = "Science"
 
words = text.split()
try:
    index = words.index(substring)
    print(f"The substring '{substring}' is found at index {index}.")
except ValueError:
    print(f"The substring '{substring}' is not present in the text.")


Output

The substring 'Science' is found at index 1.


Find The Index Of A Substring Using regular expressions

In this example, below code uses the `re` (regular expression) module to search for the substring “expressions” within the string “Regular expressions are powerful.” If the substring is found, it prints the starting index; otherwise, it indicates that the substring is not present in the text.

Python3




import re
 
text = "Regular expressions are powerful"
substring = "expressions"
 
match = re.search(substring, text)
 
if match:
    index = match.start()
    print(f"The substring '{substring}' is found at index {index}.")
else:
    print(f"The substring '{substring}' is not present in the text.")


Output

The substring 'expressions' is found at index 8.


Conclusion

Finding the index of a substring in Python is a fundamental skill for string manipulation. The methods presented in this article provide different approaches to cater to various needs. Choose the method that best suits your specific requirements, considering factors like error handling, performance, and simplicity. Whether you opt for the built-in methods like find() and index() or employ regular expressions.



Similar Reads

Maximum length palindromic substring for every index such that it starts and ends at that index
Given a string S, the task for every index of the string is to find the length of the longest palindromic substring that either starts or ends at that index. Examples: Input: S = "bababa"Output: 5 5 3 3 5 5Explanation:Longest palindromic substring starting at index 0 is "babab". Therefore, length = 5Longest palindromic substring starting at index 1
15+ min read
Find least start index of a substring from given String that contains all the given words in a contiguous manner
Given a string S and an array of equal length words (strings) arr[]. The task is to find the minimum start index of the substring that contains all the given words in a contiguous manner. If no such index is found, return -1.Note: The words can be in any sequence. Examples: Input: arr[ ] = {"bat", "bal", "cat"}, S = "hellocatbyebalbatcatyo"Output:
9 min read
Python | Get the starting index for all occurrences of given substring
Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in # a string # Initialising string ini_string = 'xbze
3 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Add Substring at Specific Index Python
In Python, String is an immutable datatype, what this means is, that there are lot many restrictions when one handles its manipulation. The problem of adding something at a position at string is not possible, without the list reconstruction. Let's discuss certain ways in which this task can be performed in Python. Ways to Insert Character Into Stri
6 min read
Minimum length of substring whose rotation generates a palindromic substring
Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string. Examples: Input: str = "abcbd" Output: 0 Explanation: No palindromic substring can be generated. There is no repeated character in the string. Input: str = "abcdeba" Output: 3 Explanation: Rotate s
7 min read
Check if substring S1 appear after any occurrence of substring S2 in given sentence
Given strings S1, S2 and S, the task is to check if every substring of S which is same as S1 has another substring of S same as S2 before it. It is given that S1 is always present as a substring in the string S. Examples: Input: S1 = "code", S2 = "geek", S = "sxygeeksgcodetecode"Output: TrueExplanation: Substring S2 is present before both the occur
4 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First occurrence of Y(= "abc"): No of occurrences of X(=
6 min read
Minimize replacement of bits to make the count of 01 substring equal to 10 substring
Given a binary string str. The task is to minimize the number of replacements of '0' by '1' or '1' by '0' to balance the binary string. A binary string is said to be balanced: "if the number of "01" substring = number of "10" substring". Examples: Input: str = "101010" Output: 1Explanation: "01" = 2 & "10" = 3. So change the last character to '
4 min read
Longest Substring of A that can be changed to Substring of B in at most T cost
Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. Note: If multiple valid substrings are possible then
13 min read
Length of recurring substring formed by repeating characters their index times in range [L, R] for Q queries
Given a string S, and two integers L and R. The task is to find the length of the substring in the given range such that each character repeats after itself exactly k times, where k is the index of the corresponding character in the alphabet. Print desired result for q queries Examples: Input: s = “cbbde”, q = 3, queries[] = { { 2, 4 }, { 3, 5 }, {
7 min read
Numpy: Index 3D array with index of last axis stored in 2D array
NumPy, or Numerical Python, is a powerful library for efficient numerical computation in Python. One of the key features of NumPy is its ability to perform advanced indexing, which allows to access and manipulate specific elements of an array based on complex conditions. In this article, we will explore how to index a 3D array using a 2D array of i
5 min read
Python - Find Product of Index Value and find the Summation
Given a List of elements, write a Python program to perform the product of index and value and compute the summation. Examples: Input : test_list = [5, 3, 4, 9, 1, 2] Output : 76 Explanation : 5 + (3*2) 6 + 12 + 36 + 5 + 12 = 76 Input : test_list = [5, 3, 4] Output : 23 Explanation : 5 + (3*2) 6 + 12 = 23 Method #1: Using loop + enumerate() In this
5 min read
Python | Find longest consecutive letter and digit substring
Given a String (may contain both letters and digits), write a Python program to find the longest consecutive letter and digit substring. Examples: Input : geeks123available Output : ('available', 123) Input : 98apple658pine Output : ('apple', 658) Approach #1 : Brute force This is the Naive or brute force approach to find the longest consecutive le
5 min read
Python | Find last occurrence of substring
Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can find the last occurrence of substring in string in Py
8 min read
Python | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.finditer() C/C++ Code import re # Initialising values ini
4 min read
Python program to find the occurrence of substring in the string
Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geek
4 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Python Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7 The desired time complexi
6 min read
Python | Find mismatch item on same index in two list
Given two list of integers, the task is to find the index at which the element of two list doesn't match. Input: Input1 = [1, 2, 3, 4] Input2 = [1, 5, 3, 6] Output: [1, 3] Explanation: At index=1 we have 2 and 5 and at index=3 we have 4 and 6 which mismatches. Below are some ways to achieve this task. Method #1: Using Iteration C/C++ Code # Python
4 min read
Python | Find minimum of each index in list of lists
Sometimes, we have encountered such problems in which we need to find the minimum of each column in a matrix i.e minimum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let's discuss certain ways in which this problem can be solved. Examples: Input : [[3, 7, 6], [1, 3, 5], [9, 3, 2]] Outpu
7 min read
Python - Find the index of Minimum element in list
Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss ways to achieve this task. Method #1: Using min() + enumerate() + l
5 min read
Difference Between find( ) and index( ) in Python
In Python, to find the index of a substring in a string can be located by python's in-built function using find() or index(). Both of them return the starting index of the substring in a string if it exists. This article discusses which one to use when and why. index() function The index() method returns the index of a substring or char inside the
2 min read
Python - Find starting index of all Nested Lists
In this article given a matrix, the task is to write a Python program to compute the starting index of all the nested lists. Example: Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]] Output : [0, 1, 5, 7, 13] Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ],
8 min read
Python - Find Index containing String in List
Given a list, the task is to write a Python Program to find the Index containing String. Example: Input: ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] Output: 0 2 3 4 7 Explanation: Index 0 2 3 4 7 contains only string. Method 1: Using type() operator in for loop By using type() operator we can get the string elements indexes fro
3 min read
Python - Find index of maximum item in list
Given a list of N integers, the task is to write a Python program to find the index of the maximum element in the Python list. Example: Input: [ 2, 4, 6, 1, 8, 5, 3 ]Output: Index of the max element in a list is 4Explanation: The max element is 8 and its position is 4. Input: [ 10, 1, 5, 3, 8, 9, 7 ]Output: Index of the max element in a list is 0Ex
6 min read
How to Find the Index for a Given Item in a Python List
We are given a list and our task is to find the index for a given item of a list in Python. In this article, we will explore each of the approaches along with their implementation. Find the Index for a Given Item in a Python ListBelow are the possible approaches to finding the index for a given item in a list in Python: Using index() functionUsing
3 min read
Find length of longest substring with at most K normal characters
Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P = "normal", Q = "00000000000000000000000000", K=1 O
12 min read
Find all substrings that are anagrams of another substring of the string S
Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at a different index. Examples: Input: S = "aba"Output: a a ab baExplanation:Following substrings are anagrams of another substring of the string S: "a": Subs
6 min read
Practice Tags :