Python .index()
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 ofstringto search. The default is 0.end(Optional): The index of the slice ofstringto 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):
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours