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 is 0.

  • 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 index method to check the index at which Java is present in the JavaScript string. We will get 0 as result.

string.index("Script")
  • We used the index method to check the index at which Script is present in the JavaScript string. We will get 4 as result.

string.index("pt", 8)
  • We used the index method to check the index at which pt is present in the JavaScript string from the 8th index. We will get 8 as result.

string.index("va", 1,5)
  • We used the index method to check the index at which va is present in the JavaScript string between the 1 to 5 index. We will get 2 as result.

print(string.index("Python"));  
  • We used the index method to check the index at which Python is present. We will get ValueError because Python is not present in the JavaScript string.

Free Resources