計算字串 str.count() 中子字串的出現次數

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

這適用於長度超過一個字元的子字串:

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

這對於只計算單個字元的 collections.Counter 是不可能的:

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