The count() Method for Counting Substring Occurrences
If the substring is found, the integer is the starting index of that substring.
From Quantity to Position
The title of this topic focuses on count(), which answers a quantity question: how many times does a substring occur? The supplied concept focuses on the closely related find() method, which answers a position question: where does the substring start? Understanding both viewpoints helps you choose the result your program needs.
When find() searches a string, it returns one integer. If the substring is found, the integer is the starting index of that substring. If the substring is not found, the result is -1. Because the result is an integer, your code can inspect it directly in a conditional statement.
| Method | Question answered | Result described in this topic |
|---|---|---|
| count() | How many occurrences are there? | An occurrence quantity |
| find() | Where does the substring start? | A starting index, or -1 when absent |
count() describes quantity, while find() supplies a position or a not-found signal.
Reading the Returned Index
Index positions are zero-indexed. That means the first character is at position 0, the next character is at position 1, and so on. The number returned by find() points to the position where the searched substring begins, not to the position after the substring.
Tracing an Email Address
Suppose the string is person@example.com and the searched substring is @. What integer should find() return?
- 1Number the characters
The first character, p, has index 0. Counting from zero places the @ character at index 6.
- 2Locate the match
The substring @ begins at index 6 in the string.
- 3Interpret the result
find()returns 6, which identifies the starting position of the searched substring.
The returned index is 6.
6Branching on -1
The most useful conditional pattern is to compare the result of find() with -1. If the result is -1, the substring is absent. If the result is not -1, the substring was found, and the returned integer gives its starting position.
position = line.find("From:")
if position == -1:
continue
print(line)- 1The current line is searched for the substring From:.
- 2If
find()returns -1, no match exists in that line. - 3continue moves to the next iteration without printing the current line.
- 4If
find()returns another integer, the substring exists and line is printed.
find()produces one integer for the current line.- The comparison checks whether the substring was not found.
- continue skips the current line when the result is -1.
- A result other than -1 allows the line to be printed.
What do you think happens?
If find() returns -1 for a line, which action should the filtering pattern take?
Reveal answer
Skip the line with continue
The source pattern interprets -1 as not found, so continue moves to the next line without printing the current one.
Filtering File Lines
The practical pattern combines a file loop, rstrip(), find(), and a conditional. The source example opens mbox-short.txt, processes each line, removes trailing whitespace, searches for a substring, and prints only lines in which the substring is present.
fhand = open("mbox-short.txt")
for line in fhand:
line = line.rstrip()
if line.find("From:") == -1:
continue
print(line)- 1The file
mbox-short.txtis opened. - 2The loop receives each line from the file.
- 3
rstrip()removes trailing whitespace from the line, including the newline character at the end of a file line. - 4
find()searches the cleaned line for From:. - 5A result of -1 causes continue to skip printing this line.
- 6A result other than -1 means the substring was found, so the line is printed.
Debugging the Search
When a substring filter behaves unexpectedly, inspect the integer returned by find() before changing the conditional. The integer tells you whether a match exists and, when it does, where the match begins. Tracing that value against the zero-indexed characters often reveals whether the search text or the expected position is incorrect.
Common mistake Treating the find() result as an occurrence count
What it looks likeA result of 6 is interpreted as six matches.
Why it failsfind()returns a starting index when the substring is found, not an occurrence quantity.Do this insteadRead the integer as the substring's starting position. Use count() when the required result is an occurrence quantity.
Common mistake Forgetting that indexes start at 0
What it looks likeThe first character is assigned index 1.
Why it failsThe source convention is zero-indexing: the first character is at position 0.
Do this insteadBegin the character trace at index 0 before checking the returned position.
Common mistake Printing every line after a failed search
What it looks likeThe code prints a line when find() returns -1.
Why it fails-1 means the substring was not found.
Do this insteadUse the -1 case to continue to the next line, and print only when the result is not -1.
Common mistake Searching a file line before removing trailing whitespace
What it looks likeThe line is passed directly to find() without rstrip().
Why it failsA line read from a file includes a newline character and other trailing whitespace may also be present.
Do this insteadCall rstrip() before searching the line.
for line in fhand:
if line.find("From:") == -1:
continue
print(line)The line is searched while its trailing newline remains.
for line in fhand:
line = line.rstrip()
if line.find("From:") == -1:
continue
print(line)Trailing whitespace is removed before the search.
Practice and Review
Write a short loop that reads lines from a file, removes trailing whitespace, searches each line for the substring "Subject:", and prints only the matching lines.
Hints
- Call
rstrip()immediately after receiving each line. - Compare the result of
find()with -1. - Use continue when the result is -1.
- 1
find()returns a single integer. A valid result identifies the substring's starting index, while -1 means that the substring was not found. Since indexes are zero-indexed, trace the returned number against character positions when debugging. For file filtering, remove trailing whitespace withrstrip(), search each line, skip lines whose result is -1, and print lines whose result is not -1.count()andfind()serve different purposes:count()reports an occurrence quantity, whilefind()reports a position or absence.
Key Takeaways
find()returns a substring's starting index or -1 when the substring is absent.- String indexes are zero-indexed, so the first character has position 0.
- Use
find()with a conditional to skip lines when the result is -1 and print lines when it is not -1. - Call
rstrip()on file lines before searching to remove trailing whitespace, including the newline character. count()answers how many occurrences exist, whilefind()identifies where a substring starts.