Python String index() Method – Find Position of a Substring

Python String index() Method

The index() method in Python is used to find the position of the first occurrence of a substring inside a string. If the substring is not found, it raises a ValueError.

Syntax

string.index(substring, start, end)

Parameters:

  • substring – The string to search for.
  • start – (Optional) The position to start searching from. Default is 0.
  • end – (Optional) The position to stop searching. Default is end of the string.

Returns:

  • The index (integer) of the first match of the substring.

Example 1: Basic Usage

text = "Python is fun"
print(text.index("fun"))
10

Explanation: The word "fun" starts at index 10 in the string.

Example 2: With Start and End Parameters

text = "banana"
print(text.index("a", 2))
3

Explanation: It starts searching from index 2, so it finds the second "a" at position 3.

Difference Between index() and find()

  • index() raises a ValueError if the substring is not found.
  • find() returns -1 instead of raising an error.

Common Error

text = "hello"
print(text.index("z"))  # Raises ValueError
ValueError: substring not found

Use Case: Validate Substring Presence

text = "apple pie"
if "pie" in text:
    print("Found at index:", text.index("pie"))
Found at index: 6

Summary

  • string.index() returns the index of the first occurrence of a substring.
  • It raises a ValueError if not found.
  • Use optional start and end to limit the search range.

Practice Problem

Write a program to find the position of the word "world" in the string "hello world" using index().

text = "hello world"
print("Index of 'world':", text.index("world"))

Expected Output:

6

Next Steps

Try using index() with different substrings and edge cases like empty strings or overlapping matches.

Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗