Edit:
As you apparently do want the count of the appearances of the whole four-character substring
, regex is probably the easiest method:
>>> import re
>>> string = 'sdkjhsgshfsdkj'
>>> substring = 'sdkj'
>>> len(re.findall(substring, string))
2
re.findall
will give you a list of all (non-overlapping) appearances of substring
in string
:
>>> re.findall('sdkj', 'sdkjhsgshfsdkj')
['sdkj', 'sdkj']
Normally, "finding a sub-string 'sdkj'
" would mean trying to locate the appearances of that complete four-character substring
within the larger string
. In this case, it appears that you simply want the sum of the counts of those four letters:
sum(string.count(c) for c in substring)
Or, more efficiently, use collections.Counter
:
from collections import Counter
counts = Counter(string)
sum(counts.get(c, 0) for c in substring)
This only iterates over string
once, rather than once for each c in substring
, so is O(m+n)
rather than O(m*n)
(where m == len(string)
and n == len(substring)
).
In action:
>>> string = "sdjskjhdvsnea"
>>> substring = "sdkj"
>>> sum(string.count(c) for c in substring)
8
>>> from collections import Counter
>>> counts = Counter(string)
>>> sum(counts.get(c, 0) for c in substring)
8
Note that you may want set(substring)
to avoid double-counting:
>>> sum(string.count(c) for c in "sdjks")
11
>>> sum(string.count(c) for c in set("sdjks"))
8