Python String index() Method

The Python string index() method can search a given string object's substring. It returns the index number or position of the substring(occurs first) in the given string. It raises a ValueError If the substring does not exist in the subject string.

Syntax:

string.index(substr, start, end)

This index() method accepts three parameters.

substr(required) This substring to be searched in subject string.
start(optional) It is an integer value specifying the index position to start the search. If not specified, the default value 0 is taken.
end(optional) It is an integer value specifying the index position where to end the search. If not specified, -1 value is taken, and mean full string length is searched
Return Value:

The lowest index position of the occurrence of the string within another string. If the given string is not found, It raises a ValueError.

In the following example, the occurrence of 'i' is searched within the string, and the index always starts with 0. Hence it will return 4 as a result.

			

# Python example of the index() method.

str = "Nothing is impossible!!!"
result = str.index("i")
print(result)

				

Output:

4

If no start and end arguments are assigned.

			

name = 'Tutorials Nation'
result = name.index('Nation')
print("Substring 'Nation' occurrence found at", result)

				

Output:

Substring 'Nation' occurrence found at 10

The following example checks, If the given string is found. If the substring is not found, the index() method raises the ValueError.

			

name = 'Tutorials Nation'
try:
    result = name.index('web')
except ValueError:
    result = -1

if result != -1:
    print("The substring is found.")
else:
    print("The substring is not found.") 

				

Output:

The substring is not found.