Definition
The index() method finds the first occurrence of the specified value. The method raises an exception if the value is not found. It is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found.
Syntax
string.index(value, start, end)
Parameters
Parameter | Description |
---|---|
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
Examples:
myStr = "Welcome to the Python tutorials."
result = myStr.index("Welcome")
print(result)
# find the first occurrence of the letter "y"
result = myStr.index("y")
print(result)
# find the first occurrence of the letter "y" when you only search between position 6 and 17?
result = myStr.index("y", 6, 17)
print(result)