Python String index() Method
Example
Where is the word "welcome" in the text?
txt = "Hello, welcome to my world." x = txt.index("welcome") print(x)
Definition and Usage
The index() method searches for the first occurrence of the specified value.
If the value is not found, the index() method will raise an exception.
The index() method is almost the same as the find() method, the only difference is that if the value is not found, the find() method will return -1. (See the following examples)
Syntax
string.index(value, start, end)
Parameter Value
Parameter | Description |
---|---|
value | Required. The value to be searched for. |
start | Optional. Where to start the search. The default is 0. |
end | Optional. Where to end the search. The default is the end of the string. |
More Examples
Example
Where does the letter "e" first appear in the text?
txt = "Hello, welcome to my world." x = txt.index("e") print(x)
Example
If the search is only between positions 5 and 10, where does the letter "e" first appear?
txt = "Hello, welcome to my world." x = txt.index("e", 5, 10) print(x)
Example
If the value is not found, the find() method returns -1, but the index() method will raise an exception:
txt = "Hello, welcome to my world." print(txt.find("q")) print(txt.index("q"))