Python String index() Method

Python String index() method is used to find the first occurrence of a specified substring within a string.

This method is similar to the find() method for strings. The main difference is that while the find() method returns -1 when the substring is not found, the index() method raises a ValueError.

Syntax

string.index(value, start, end)

Parameters

  1. value(required): It is the substring you are searching for in the original string.
  2. start(optional): It is the starting index where the search begins. The default is 0.
  3. end(optional): It is the ending index where the search ends. The default is to the end of the string.

Return value

If a substring exists inside the string, it returns the index of the first occurrence of the substring. If the substring doesn’t exist inside the string, it raises a ValueError exception.

Visual Representation

Example 1: How to Use Python string index() Method

str = 'Expecto Patronum'
extract = str.index('num')

print(extract)

Output

13

Example 2: Passing start and end parameters

Visual Representation of Python String index() Method (Passing Start and end arguments)

str = 'Leo Messi'
sample = str.index('M', 0, 6)

print(sample)

Output

4

Example 3: ValueError: substring not found

str1 = "Hello! This is Krunal"
str2 = "venom"
result = str1.index(str2, 25)

print("The index where the substring is found:", result)

Output

ValueError: substring not found

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.