Python str.index() function


str.index() Function in Python

The str.index() function in Python is similar to str.find(), as it is used to search for a specified substring within a string and return the index of its first occurrence. However, there is a key difference: if the substring is not found, str.index() raises a ValueError instead of returning -1. This makes str.index() useful when you expect the substring to be present and want to handle cases where it is not found with an exception.

Syntax:

string.index(substring, start, end)
  • substring: The substring you want to search for.
  • start (optional): The starting index from where the search should begin. The default is 0.
  • end (optional): The ending index where the search should stop. The default is the end of the string.

Example 1: Basic usage

# Example 1: Finding a substring my_string = "Hello, world!" index = my_string.index("world") print(index) # Output: 7

In this example:

  • The substring "world" is found at index 7 in the string "Hello, world!".

Example 2: Substring not found

# Example 2: Substring not found my_string = "Hello, world!" try: index = my_string.index("Python") except ValueError as e: print(e) # Output: substring not found

Here:

  • The substring "Python" is not found in the original string, causing str.index() to raise a ValueError, which is caught and printed.

Example 3: Specifying start and end indices

# Example 3: Specifying start and end indices my_string = "Hello, world! Welcome to the world of Python." index = my_string.index("world", 10) print(index) # Output: 27

In this case:

  • The search for "world" starts from index 10, and the first occurrence of "world" after that is found at index 27.

Example 4: Using index() with overlapping substrings

# Example 4: Overlapping substrings my_string = "banana" index = my_string.index("ana") print(index) # Output: 1

Here:

  • The substring "ana" is found starting at index 1.

Key Points:

  • str.index() returns the index of the first occurrence of the specified substring.
  • It is case-sensitive, meaning "Hello" and "hello" are considered different.
  • If the substring is not found, it raises a ValueError.
  • You can specify optional start and end parameters to limit the search range within the string.
  • The function does not modify the original string.

Example 5: Case sensitivity

# Example 5: Case sensitivity my_string = "Hello, world!" try: index = my_string.index("hello") except ValueError as e: print(e) # Output: substring not found

In this example:

  • The search for "hello" (lowercase) raises a ValueError because it is not found in the original string.

Example 6: Multiple occurrences

# Example 6: Multiple occurrences my_string = "apple banana apple orange" index = my_string.index("apple") print(index) # Output: 0

Here:

  • The first occurrence of "apple" is found at index 0, even though there is a second occurrence later in the string.