78 of 151 menu

The index method

The index method returns the index of the first substring match in the string. In the first parameter of the method, we specify the substring we need, in the second and third optional parameters - the index of the beginning and end of the search, respectively. If the substring is not found, the method will throw an exception.

Syntax

string.index(substring, [start searching], [end of search])

Example

Let's find the position of the substring 'a':

txt = 'abcadea' print(txt.index('a'))

Result of code execution:

0

Example

Let's now specify the search boundaries:

txt = 'abcadea' print(txt.index('a', 1, 4))

Result of code execution:

3

See also

  • method rindex,
    which returns the highest index of the substring match at the end of the string
  • method find,
    which returns the index of the first match of a substring in a string
  • method startswith,
    which checks a substring from the beginning of a string
  • method endswith,
    which checks for a substring from the end of a string
  • method count,
    which returns the number of occurrences of a substring in a string
swrufrazkk