Python String find() Method
Example
Where is the word "welcome" in the text?
txt = "Hello, welcome to my world." x = txt.find("welcome") print(x)
Definition and Usage
The find() method searches for the first occurrence of the specified value.
If the value is not found, the find() method returns -1.
The find() method is almost the same as the index() method, the only difference is that if the value is not found, the index() method will raise an exception. (See the example below)
Syntax
string.find(value, start, end)
Parameter Value
Parameter | Description |
---|---|
value | Required. The value to be searched for. |
start | Optional. The position to start the search. The default is 0. |
end | Optional. The position to end the search. The default is the end of the string. |
More Examples
Example
The position of the letter "e" in the text where it first appears:
txt = "Hello, welcome to my world." x = txt.find("e") print(x)
Example
If only searching for the first occurrence of the letter "e" in the text from position 5 to 10:
txt = "Hello, welcome to my world." x = txt.find("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"))