Python String index() Method – Tutorial with Examples

Python String index() Method

The index() method is a built-in method in Python that searches for the specified substring in a string and returns the position of the first occurrence of the substring. If the substring is not found in the string, it raises a ValueError.

Syntax

The syntax of the index() method is as follows:

string.index(substring, start, end)

Here, string is the string in which the substring is to be searched, substring is the string that is to be searched, start is the starting index of the search (optional, defaults to 0), and end is the ending index of the search (optional, defaults to the end of the string).

Return Value

The index() method returns the position of the first occurrence of the specified substring in the string. If the substring is not found in the string, it raises a ValueError.

Examples

Here are three different examples of how to use the index() method in Python:

Example 1: Finding the Index of a Substring

The following example demonstrates how to use the index() method to find the index of a substring:

string = "hello world"
index = string.index("world")
print(index)

Output:

6

In this example, we define a string and use the index() method to find the index of the substring “world” in the string.

Example 2: Finding the Index of a Substring with Start and End Index

The following example demonstrates how to use the index() method to find the index of a substring with a start and end index:

string = "hello world"
index = string.index("o", 4, 7)
print(index)

Output:

4

In this example, we define a string and use the index() method to find the index of the substring “o” in the string, starting from index 4 and ending at index 7.

Example 3: Handling a ValueError

The following example demonstrates how to handle a ValueError that is raised when the substring is not found in the string:

string = "hello world"
try:
    index = string.index("test")
    print(index)
except ValueError:
    print("Substring not found")

Output:

Substring not found

In this example, we define a string and use the index() method to find the index of the substring “test” in the string. Since “test” is not found in the string, a ValueError is raised. We catch the ValueError using a try-except block and print a message indicating that the substring was not found.

Use Cases

The index() method is useful in situations where you need to find the position of a specific substring within a string. This can be helpful when manipulating or processing text data, such as in natural language processing, web scraping, or data cleaning tasks. It can also be useful in searching for specific patterns within a larger string.

Leave a Reply

Your email address will not be published. Required fields are marked *