Python String find() Method
The find() method in Python helps you locate the position of a substring inside another string. It's a safe way to check if a word or character exists and find where it appears first.
Syntax
string.find(substring, start, end)
Parameters:
substring– The string you want to find inside the main string (required).start– The position to start the search (optional).end– The position to end the search (optional).
Returns:
- Index (integer) of the first occurrence of the substring.
- Returns
-1if the substring is not found.
Example 1: Basic Usage
text = "Python programming is fun"
position = text.find("programming")
print(position)
7
Why? Because the word "programming" starts at index 7 in the string.
Example 2: Substring Not Found
print("apple".find("z"))
-1
Note: find() doesn't crash if the substring isn't found – it simply returns -1.
Example 3: Using Start and End
text = "learn learn learn"
position = text.find("learn", 6)
print(position)
6
Here, we told Python to start looking from index 6. It finds the second "learn" starting at index 6.
Real-Life Use Case
Use find() to check if a user input contains certain keywords:
message = "Please confirm your email address"
if message.find("confirm") != -1:
print("Confirmation keyword found!")
Confirmation keyword found!
Difference Between find() and index()
find()returns-1if not foundindex()raises aValueErrorif not found
Common Mistakes
- Forgetting that
find()is case-sensitive ("Hello".find("h")returns-1) - Using
== 0instead of!= -1when checking if something exists
Summary
find()helps locate substrings inside strings- Returns index if found, or
-1if not - Safe to use even if the substring doesn't exist
Practice Problem
Ask the user to enter a sentence and search for the word "Python". Print the result.
sentence = input("Enter a sentence: ")
index = sentence.find("Python")
if index != -1:
print("Found 'Python' at index", index)
else:
print("'Python' not found")
Comments
Loading comments...