Concepts / The count() Method for Counting Substring Occurrences

The count() Method for Counting Substring Occurrences

If the substring is found, the integer is the starting index of that substring.

  • Programming

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.

MethodQuestion answeredResult 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.

pindex 06find resulteindex 1rindex 2sindex 3oindex 4nindex 5@index 6starts at
How does find() map the substring @ to its starting character position in an email address?
Worked example

Tracing an Email Address

Suppose the string is person@example.com and the searched substring is @. What integer should find() return?

  1. 1
    Number the characters

    The first character, p, has index 0. Counting from zero places the @ character at index 6.

  2. 2
    Locate the match

    The substring @ begins at index 6 in the string.

  3. 3
    Interpret the result

    find() returns 6, which identifies the starting position of the searched substring.

Result

The returned index is 6.

python
Output
6

Branching 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.

find() resultsingle integerResult is -1substring absent?continueskip this lineprint linesubstring foundinspectyesno
What control-flow branch occurs when find() returns a valid index versus -1?
Code walkthrough
position = line.find("From:")
if position == -1:
    continue
print(line)
  1. 1
    The current line is searched for the substring From:.
  2. 2
    If find() returns -1, no match exists in that line.
  3. 3
    continue moves to the next iteration without printing the current line.
  4. 4
    If 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?

  • Print the line

  • Skip the line with continue

  • Treat -1 as the match position

Reveal answer
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.

mbox-short.txtsource filecurrent linetrailing whitespace removedfind()search substringnext lineresult is -1printed linesresult is not -1readsearch-1not -1
How does each line move through the search condition, and where do matching lines go?
python
Code walkthrough
fhand = open("mbox-short.txt")
for line in fhand:
    line = line.rstrip()
    if line.find("From:") == -1:
        continue
    print(line)
  1. 1
    The file mbox-short.txt is opened.
  2. 2
    The loop receives each line from the file.
  3. 3
    rstrip() removes trailing whitespace from the line, including the newline character at the end of a file line.
  4. 4
    find() searches the cleaned line for From:.
  5. 5
    A result of -1 causes continue to skip printing this line.
  6. 6
    A 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 like

    A result of 6 is interpreted as six matches.

    Why it fails

    find() returns a starting index when the substring is found, not an occurrence quantity.

    Do this instead

    Read 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 like

    The first character is assigned index 1.

    Why it fails

    The source convention is zero-indexing: the first character is at position 0.

    Do this instead

    Begin the character trace at index 0 before checking the returned position.

  • Common mistake

    Printing every line after a failed search

    What it looks like

    The code prints a line when find() returns -1.

    Why it fails

    -1 means the substring was not found.

    Do this instead

    Use 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 like

    The line is passed directly to find() without rstrip().

    Why it fails

    A line read from a file includes a newline character and other trailing whitespace may also be present.

    Do this instead

    Call rstrip() before searching the line.

Before
for line in fhand:
    if line.find("From:") == -1:
        continue
    print(line)

The line is searched while its trailing newline remains.

After
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

MEDIUM

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. 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 with rstrip(), search each line, skip lines whose result is -1, and print lines whose result is not -1. count() and find() serve different purposes: count() reports an occurrence quantity, while find() 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, while find() identifies where a substring starts.

Related concepts

More concepts starting with T