String index() Method in Python

Python String index() Method

The index() method in Python is used to find the index of the first occurrence of a substring within a given string. It is similar to the find() method, but instead of returning -1 when the substring is not found, it raises a ValueError exception.Here's the syntax of the index() method:

string.index(substring, start, end)

Parameters:

  • substring: The substring that you want to find within the original string.
  • start (optional): The index from which the search for the substring begins. It is an optional parameter, and if not provided, the search starts from the beginning of the string.
  • end (optional): The index at which the search for the substring ends. It is an optional parameter, and if not provided, the search goes until the end of the string.

Example:

# Example string
original_string = "Hello, world!"

# Finding the index of the substring "world" in the string
index = original_string.index("world")

print("Original String:", original_string)
print("Index of 'world':", index)

Output:

Original String: Hello, world!
Index of 'world': 7

In this example, we used the index() method to find the index of the substring "world" in the original string. The method returned 7, which is the index of the first character of the substring "world" within the original string.However, if the substring is not found in the string, the index() method raises a ValueError exception. For example:

# Example string
original_string = "Hello, world!"

try:
    # Trying to find the index of the substring "Python"
    index = original_string.index("Python")
    print("Index of 'Python':", index)
except ValueError as e:
    print("Substring 'Python' not found:", e)

Output:

Substring 'Python' not found: substring not found

In this case, since the substring "Python" is not present in the original string, the index() method raises a ValueError exception with the message "substring not found". To avoid this exception, you can use the find() method, which returns -1 when the substring is not found.