String Methods
count()
Count how many non-overlapping times some text appears.
str.count(sub, start=0, end=len(str))
str.count() returns the number of non-overlapping occurrences of substring sub in the range [start, end].
Parameters
| Name | Description |
|---|---|
| sub | The text to count. |
| start | Optional starting position. |
| end | Optional position where the search stops. |
Returns
An integer count.
Try it
Run it and change it
text = "banana"
print(text.count("an"))
Worth knowing
- Non-overlapping matches:
'aaaa'.count('aa')returns2, not3, because matched characters are not reused.