.index()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Oct 19, 2021Updated Nov 1, 2021
Contribute to Docs

The .index() string method searches through a string variable for the occurrence of a pattern or a substring.

If the substring is not found, a ValueError will be raised.

Syntax

string.index(pattern, start, end)

In the above syntax for the .index() method:

  • pattern (Required): The pattern or substring to search for.
  • start (Optional): The starting index of string to search. The default is 0.
  • end (Optional): The index of the slice of string to search up to, non-inclusive. The default is end of the string.

Example 1

Use .index() method to search for the occurrence of 'Python' in the string variable my_string:

my_string = 'Learning Python is fun!'
index = my_string.index('Python')
print(index)
# Output: 9

The starting index of the substring 'Python' is 9.

Example 2

Use .index() method to search for the occurrence of 'Coding' in the string variable my_string:

my_string = 'Learning Python is fun!'
my_string.index('Coding')

There will be an error:

ValueError: substring not found

Codebyte Example

Use .index() method to search for the occurrence of 'code' in a slice of the string variable my_string (i.e. from the character at index 8 up to, but not including, the character at index 16):

Code
Output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy