What is the string.index method in Python?
The index method returns the index of the first occurrence of a substring in a string. If the substring is not present in the string, then the ValueError: substring not found exception is thrown.
Syntax
string.index(substring [, start[, end]] )
Arguments
-
substring: The string to be searched. -
start: The index from which the substring search should start. This is an optional value, and by default the value is0. -
end: The index to which the substring search should happen. This is an optional value, and by default the value is the length of the string.
Return value
The return value is the first index at which the substring is found. If the substring is not present, an exception is thrown.
Example
string = "JavaScript";print("The index of Java in JavaScript is")print(string.index("Java"));print("\nThe index of Script in JavaScript is")print(string.index("Script"));print("\nThe searching for 'pt' in JavaScript from index 8")print(string.index("pt", 8));print("\nThe searching for 'va' in JavaScript from index 1 and 5")print(string.index("va", 1,5));try:print("\nThe index of Python in JavaScript is")print(string.index("Python"));except ValueError as ve:print("Error", ve)
In the above code, we created a string, JavaScript:
string.index("Java")
- We used the
indexmethod to check the index at whichJavais present in theJavaScriptstring. We will get0as result.
string.index("Script")
- We used the
indexmethod to check the index at whichScriptis present in theJavaScriptstring. We will get4as result.
string.index("pt", 8)
- We used the
indexmethod to check the index at whichptis present in theJavaScriptstring from the8thindex. We will get8as result.
string.index("va", 1,5)
- We used the
indexmethod to check the index at whichvais present in theJavaScriptstring between the 1 to 5 index. We will get2as result.
print(string.index("Python"));
- We used the
indexmethod to check the index at whichPythonis present. We will getValueErrorbecausePythonis not present in theJavaScriptstring.