Count number of occurrences of a substring in a string
Use str.count(sub) for quickly counting substrings in a main string:
This method returns the count of non-overlapping "hello" occurrences within the txt string.
Battle with overlapping substrings
If you wish to combat against overlapping substrings, str.count() comes up short. In this fight, a regular expression with a lookahead assertion is your key weapon:
The pattern finds all instances where "hello" starts, even if it begins the next "hello".
The old-school way: manual counting
If pre-built methods aren't your style, you can always go the hand-crafted artisan way — manual traversal:
In this function, find() starts searching from the last found position, incrementing a counter each time the substring is found.
Heads up: case sensitivity and normalization
Remember str.count() is case sensitive. For case-insensitive tally, normalize both strings to lower or upper:
Also, normalize your string to handle Unicode anomalies.
Performance tales and wails
While neat, manual counting and regex may cause performance deterioration compared to str.count(). When dealing with long strings, efficiency matters.
Edge of the edge cases
Stay vigilant with edge cases like empty strings or substrings. They might mislead script outcomes:
Was this article helpful?