Searching in Strings
Use the in operator, .find(), and .count() to search text
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Three ways to search
| Expression | Returns | Use when |
|---|---|---|
"word" in text | True or False | You need to know if a word is present |
text.find("word") | Index of first match, or -1 | You need the position |
text.count("word") | Number of occurrences | You need how many times it appears |
The in operator
in is the simplest search — it returns True or False.
"Python" in "I love Python" # True
"Java" in "I love Python" # False.find()
.find() returns the index where the search term first appears. It returns -1 if the term is not found.
text = "Hello, world!"
print(text.find("world")) # 7
print(text.find("Java")) # -1.count()
.count() counts how many times a substring appears. The search is case-sensitive.
print("banana".count("a")) # 3
Instructions
Search a string using the in operator, .find(), and .count().
- Assign
"The quick brown fox jumps over the lazy dog"totext. - Call
print("fox" in text). - Call
print("cat" in text). - Assign
text.find("fox")toposition. Callprint(position). - Assign
text.count("the")tocount. Callprint(count). - Call
print(text.find("cat")).
# Step 1: Assign text # Step 2: Print whether "fox" is in text # Step 3: Print whether "cat" is in text # Step 4: Find the position of "fox" and print it # Step 5: Count occurrences of "the" and print # Step 6: Print the result of finding "cat"
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding