The index() function is a built-in function in Python that is used to find the index of the first occurrence of a substring within a string. It is similar to the find() function, but raises a ValueError exception if the substring is not found, whereas find() returns -1 in that case.
The index() function takes two arguments: the substring to search for, and an optional start index. If the start index is not specified, the search begins at the beginning of the string.
Here is an example of using the index() function to find the index of a substring within a string:
string = "Hello, world!"substring = "world"index = string.index(substring)print(index) # Output: 7 |
In this example, the index() function is used to find the index of the substring "world" within the string "Hello, world!". The function returns the value 7, which is the index of the first occurrence of the substring.
If the substring is not found within the string, the index() function raises a ValueError exception. Here is an example of using the index() function with a substring that is not in the string:
string = "Hello, world!"substring = "Python"index = string.index(substring) |
This code would raise a ValueError exception with the message "substring not found". To avoid this exception, you can use the in keyword to check if the substring is in the string before calling the index() function:
string = "Hello, world!"substring = "Python"if substring in string: index = string.index(substring) print(index)else: print("Substring not found") |
In this example, the in keyword is used to check if the substring "Python" is in the string "Hello, world!". Since the substring is not in the string, the code prints the message "Substring not found" instead of raising an exception.