Python String index Method

The Python index method functions similarly to the find method, with the distinction that it raises an error when a match is not found. This method provides the index of the first occurrence of a specified substring, and it will trigger an error if no match exists.

Signature

Example

index(sub[, start[, end]])

Parameters

  • sub : substring
  • start : start index a range
  • end : last index of the range
  • Return Type

If the substring is located, it returns the index of that substring; if not, it raises a ValueError.

Let us explore a few examples to gain a better understanding of the index method.

Python String index Method Example 1

Example

# Python index() function example
# Variable declaration
str = "Welcome to our tutorial."
# Calling function
str2 = str.index("at")
# Displaying result
print(str2)

Output:

Python String index Method Example 2

An error is thrown if the substring is not found.

Example

# Python index() function example
# Variable declaration
str = "Welcome to our tutorial."
# Calling function
str2 = str.index("ate")
# Displaying result
print(str2)

Output:

Output

ValueError: substring not found

Python String index Method Example 3

Additionally, we can provide start and end indices as arguments to allow for a more tailored processing experience.

Example

# Python index() function example
# Variable declaration
str = "Welcome to our tutorial."
# Calling function
str2 = str.index("p",19,21)
# Displaying result
print("p is present at :",str2,"index")

Output:

Output

p is present at : 20 index

Input Required

This code uses input(). Please provide values below: