PythonMastery
Python programs · Strings · beginner

Count occurrences of a substring in Python

Count how many times one piece of text appears inside another with str.count(). Also shows overlapping matches and a case-insensitive count.

The string method count() gives the number of times a substring (a piece of a string) appears in a string.

The program

python
text = input("Text: ")
part = input("Count what: ")

print(f'"{part}" appears {text.count(part)} times')

Typed in this example: she sells sea shells by the sea shore, sea. Press Run to type your own.

output
Text: she sells sea shells by the sea shore
Count what: sea
"sea" appears 2 times

How it works

Overlapping matches

Because count() continues after the end of each match, matches that overlap are not counted. "banana" contains "ana" twice (at positions 1 and 3), but the two matches share an "a":

python
print("banana".count("ana"))
output
1

To count overlapping matches too, check every starting position yourself:

python
def count_overlapping(text, part):
    count = 0
    for i in range(len(text) - len(part) + 1):
        if text[i:i + len(part)] == part:
            count += 1
    return count


print(count_overlapping("banana", "ana"))
print(count_overlapping("aaaa", "aa"))
output
2
3

Learn the idea: Working with Strings, Loops: for, while, and the Pythonic Patterns