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:
- substr: (Required) The substring whose index has to be found.
- start: (Optional) The starting index position from where the searching should start in the string. Default is 0.
- 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.
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'))
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.
greet='Hello World'
print('Index of l: ', greet.index('l'))
print('Index of o: ', greet.index('o'))
Index of l: 2
Index of o: 4
The index()
method performs case-sensitive search. It throws ValueError
if a substring not found.
greet='Hello World'
print(greet.index('h')) # throws error: substring not found
print(greet.index('hello')) # throws error
ValueError: substring not found
ValueError: substring not found
If a given substring could not be found then it will throw an error.
mystr='TutorialsTeacher is a free online learning website'
print(mystr.index('python'))
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.
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
27
ValueError: substring not found