The find() method in Python is a string method that returns the lowest index within the string where a specified substring is found. If the substring is not found, it returns -1. It takes the substring to search for as its argument and can also take optional parameters for the start and end position to limit the search within a specific range of the string.
Parameter Values
| Parameter | Description |
|---|---|
| sub | The |
| start | The |
| end | The |
Return Values
The find() method returns an int indicating the index or -1 if not found.
How to Use find() in Python
The find() method returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1.
text = 'Hello, World!'
index = text.find('World')
print(index) # Output: 7The find() method can also take optional parameters for start and end indexes to search within a specific range of the string.
text = 'Python is awesome!'
index = text.find('is', 5, 15)
print(index) # Output: 7If the value is not found within the specified range, the method returns -1.
text = 'Python is awesome!'
index = text.find('is', 12, 15)
print(index) # Output: -1