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
text.count(part)searches from left to right. Each time it findspart, it adds 1 and continues searching after the end of that match.- The search is case-sensitive: "Sea" and "sea" are different. To ignore case, make both strings small first:
text.lower().count(part.lower()).
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
range(len(text) - len(part) + 1)gives every position wherepartcould still fit.text[i:i + len(part)]is the slice of the same length aspart, starting at positioni.