![]() |
VOOZH | about |
The index() method in Python is used to find the position of a specified substring within a given string. It is similar to the find() method but raises a ValueError if the substring is not found, while find() returns -1. This can be helpful when we want to ensure that the substring exists in the string before proceeding. Let's see a simple use of index():
7
Explanation: index() method searches for the substring "prog" within "Python programming" and returns starting index 7.
s.index(substring, start=0, end=len(s))
Parameters:
Return Type:
Let's understand the use of index() with the help of some examples.
This code demonstrates how to find the index of a substring within a string using the index() method.
7
Explanation:
This code demonstrates how to find the index of a substring within a specific range of a string using the index() method with optional start and end parameters.
19
Explanation:
Related Articles: