Tutorialsteacher

Follow Us

Python String index() Method

The index() method returns the index of the first occurence of a substring in the given string. It is same as the find() method except that if a substring is not found, then it raises an exception.

Syntax:

str.index(substr, start, end)

Parameters:

  1. substr: (Required) The substring whose index has to be found.
  2. start: (Optional) The starting index position from where the searching should start in the string. Default is 0.
  3. end: (Optional) The ending index position untill the searching should happen. Default is end of the string.

Return Value:

An integer value indicating an index of the specified substring.

The following examples demonstrates index() method.

Example: index()
greet='Hello World!' print('Index of H: ', greet.index('H')) print('Index of e: ', greet.index('e')) print('Index of l: ', greet.index('l')) print('Index of World: ', greet.index('World'))
Output
Index of H: 0 Index of e: 1 Index of l: 2 Index of World: 6

The index() method returns an index of the first occurance only.

Example: index() returns first occurance index
greet='Hello World' print('Index of l: ', greet.index('l')) print('Index of o: ', greet.index('o'))
Output
Index of l: 2 Index of o: 4

The index() method performs case-sensitive search. It throws ValueError if a substring not found.

Example: Case-sensitive index() Method
greet='Hello World' print(greet.index('h')) # throws error: substring not found print(greet.index('hello')) # throws error
Output
ValueError: substring not found ValueError: substring not found

If a given substring could not be found then it will throw an error.

Example: index()
mystr='TutorialsTeacher is a free online learning website' print(mystr.index('python'))
Output
Traceback (most recent call last) <ipython-input-3-a72aac0824ca> in <module> 1 str='TutorialsTeacher is a free online learning website' ----> 2 print(str.index('python')) ValueError: substring not found

Use start and end parameter to limit the search of a substring between the specified starting and ending index.

Example: index() with start and end parameters
mystr='tutorialsteacher is a free tutorials website' print(mystr.index('tutorials',10)) # search starts from 10th index print(mystr.index('tutorials',1, 26)) # throws error; searches between 1st and 26th index
Output
27 ValueError: substring not found