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, because a string yields characters rather than longer substrings:

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

Feedback about page:

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



Table Of Contents