Python String find() Method

The find() method is used to search for a substring within a string. It returns the lowest index where the substring is found. If the substring is not found, it returns -1.

Syntax

string.find(substring, start, end)

Parameters

substring: The string you want to search for.

start (Optional): The starting index to begin the search. Default is 0.

end (Optional): The ending index to stop the search. Default is the end of the string.

Return Value

Returns the lowest index where the substring is found, or -1 if it is not found.

Examples

Basic Usage

text = "Hello, welcome to Toronto"
index = text.find("welcome")
print(index) # Output: 7

If substring is not found

The find() method returns -1 if the substring is not found within the string.

text = "Hello, welcome to Toronto"
index = text.find("London")
print(index) # Output: -1

With start Parameter

text = "hello hello hello"
index = text.find("hello", 3)
print(index) # Output: 6

In this example, the substring "hello" appears three times at the index 0, 6, and 12. By passing 3 as the start parameter to the find() method, the search starts at the index 3, skipping the first occurrence of the substring "hello" at index 0.

As a result, it returns the index of the next occurrence of the substring "hello" after the start index, which is 6.

With start and end Parameters

text = "hello hello hello"
index = text.find("hello", 6, 10)
print(index) # Output: -1

In this example, the substring "hello" appears three times at the index 0, 6, and 12. By passing 6 as the start and 10 as the end parameters to the find() method, it searches for the substring "hello" from index 6 up to (but not including) index 10. Since the substring doesn’t exist with the start and end index, it returns -1.

Finding a Single Character

The find() method can also be used to locate the first occurrence of a single character in a string.

text = "banana"
index = text.find("a")
print(index) # Output: 1

Case-Sensitive

The find() method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters.

text = "Hello, welcome to Toronto"
index = text.find("toronto")
print(index) # Output: -1

In this example, the find() method returns -1 because it is case-sensitive. It looks for the exact lowercase substring "toronto" but the text contains "Toronto" with an uppercase "T". Since the cases do not match, no match is found.

find() vs index()

The find() method is similar to the index() method. Both return the lowest index where the specified substring is found. The key difference is that find() method returns -1 if the substring is not found, while index() method raises a ValueError.