Counting the occurrences of a substring in a string str.count

suggest change
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})

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents