Searching in Strings
Exit

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

ExpressionReturnsUse when
"word" in textTrue or FalseYou need to know if a word is present
text.find("word")Index of first match, or -1You need the position
text.count("word")Number of occurrencesYou 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().

  1. Assign "The quick brown fox jumps over the lazy dog" to text.
  2. Call print("fox" in text).
  3. Call print("cat" in text).
  4. Assign text.find("fox") to position. Call print(position).
  5. Assign text.count("the") to count. Call print(count).
  6. Call print(text.find("cat")).