Learning the find() Method for Strings
In this tutorial, you’ll learn how to use the find() method in Python to search for specific text within a string. By the end, you’ll know how to locate words, letters, or phrases and understand their positions in a string.
In this tutorial, you’ll learn how to use the find() method in Python to search for specific text within a string. By the end, you’ll know how to locate words, letters, or phrases and understand their positions in a string.
1. What Is the find() Method?
The find() method searches a string for a specific substring (text) and returns the position (index) where it starts. If the substring isn’t found, it returns -1.
Here’s the syntax:
string.find(substring)
string: The text you want to search in.
substring: The text you’re looking for.
2. Example: Searching for a Word
sentence = "Python is amazing"
position = sentence.find("is")
print(position)
Output:
7
Explanation:
"is" starts at index 7 in the string.
3. Case Matters!
The find() method is case-sensitive.
text = "Hello World"
print(text.find("world")) # Lowercase 'world'
Output:
-1
Explanation:
The word "world" isn’t found because it doesn’t match "World" exactly.
4. Searching from a Specific Position
You can specify where to start the search using an optional second argument.
sentence = "I love Python because Python is fun"
position = sentence.find("Python", 10)
print(position)
Output:
20
Explanation:
The search starts at index 10, skipping the first occurrence of "Python".
5. Practical Uses of find()
Example 1: Checking if a Word Exists
message = "Do your homework!"
if message.find("homework") != -1:
print("The word 'homework' is in the sentence.")
else:
print("The word 'homework' is not in the sentence.")
Output:
The word 'homework' is in the sentence.
Example 2: Extracting Part of a String
email = "student123@gmail.com"
at_index = email.find("@")
print("Username:", email[:at_index])
Output:
Username: student123
6. Practice Exercises
Exercise 1: Find a Word
Write a program to find the position of the word "Python" in the sentence:
"I am learning Python programming."
Exercise 2: Case Sensitivity
Run the following code and explain why it prints -1:
text = "Python is fun"
print(text.find("python"))
Exercise 3: Find and Extract
Given the sentence:
"My favorite fruit is mango."
Write a program to find the position of "mango" and extract it using slicing.
Exercise 4: Check for a Word
Write a program that checks if the word "dog" is in the sentence:
"The quick brown fox jumps over the lazy dog."
7. Bonus Challenge
Create a program that extracts the domain name from an email address.
Example:
Input: user@example.com
Output: example.com
8. What’s Next?
Great job learning about the find() method! It’s a handy tool for searching and working with strings. Keep practicing, and you’ll become a Python pro in no time! 🎉