Use find() Function in Python with Example

The `find()` function in Python is a string method used to search for the first occurrence of a specified substring within another string. It returns the index of the first character of the substring if found; otherwise, it returns `-1`.

Syntax

string.find(substring, start, end)

– substring: The string to be searched within the main string.
– start(optional): The starting index from where the search begins. The default is `0`.
– end (optional): The ending index where the search ends. The default is the length of the string.

Example

Here’s a basic example of how to use the `find()` function:

text = "Hello, welcome to the world of Python programming."
# Find the first occurrence of the substring 'Python'
index = text.find("Python")
if index != -1:
print(f"Substring 'Python' found at index: {index}")
else:
print("Substring not found.")

Output

Substring 'Python' found at index: 30

Explanation

– The `find()` method searches for the substring `”Python”` in the string `”Hello, welcome to the world of Python programming.”`.
– It returns the index `30`, which is the starting index of the substring `”Python”`.
– If the substring is not found, the method would return `-1`.

Example with `start` and `end` Parameters

You can also specify the starting and ending indices for the search:

text = "Hello, welcome to the world of Python programming."
# Find the substring 'o' starting from index 5 and ending at index 20
index = text.find('o', 5, 20)
if index != -1:
print(f"Substring 'o' found at index: {index}")
else:
print("Substring not found in the specified range.")

Output

Substring 'o' found at index: 8

Explanation

– Here, the `find()` method searches for the first occurrence of the substring `”o”` between the indices 5 and 20.
– It returns `8`, which is the index of the first occurrence of `”o”` within the specified range.