Python Language Counting Counting the occurrences of a substring in a string: str.count()

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

astring = 'thisisashorttext'
astring.count('t')
# Out: 4

This works even for substrings longer than one character:

astring.count('th')
# Out: 1
astring.count('is')
# Out: 2
astring.count('text')
# Out: 1

which would not be possible with collections.Counter which only counts single characters:

from collections import Counter
Counter(astring)
# Out: Counter({'a': 1, 'e': 1, 'h': 2, 'i': 2, 'o': 1, 'r': 1, 's': 3, 't': 4, 'x': 1})


Got any Python Language Question?