Python String index() Method
Returns the index of the first matching substring within the given string. If the index is not found, Python throws a ValueError
exception.
Syntax
Python
Copy Code
string.index(value, start = None, end = None)
Parameters
Parameter | Description |
---|---|
value |
Required. The value to search for. |
start |
Optional. The index at which to start searching. The default is None meaning 0. |
end |
Optional. The index at which to stop searching. The default is None meaning the end of the string. |
Example
Python
Copy Code
str = 'The quick brown fox jumped over the lazy dog' print(str.index('brown')) try: print(str.index('horse')) except ValueError: print('The string "horse" was not found!')
Output
10 The string "horse" was not found!