Peter Chen Peter Chen - 1 month ago 8
Python Question

Determine how many times a substring occurs adjacently in a string in Python

I want to calculate how many times a substring occurs "adjacently" in a string,
for example, given the string "8448442844" and the substring "844", I want the result "2".
I know the string.count(substring) function, in this example, using this function, I will get the result "3". But I want the result "2". How can I achieve my goal, thanks in advance.

Answer

This will work just fine for any adjacent sub string:

a = "8448442844"
sol, sub = 0, "844"

for i in range(1, a.count(sub)+1):
  if a.count(str(sub*i)): sol = i
  else: break
print (sol)
# 2

Can also convert to a one-liner using Comprehension and sum:

a, sub = "8448442844", "844"
sol = sum([1 for x in range(1, a.count(sub)+1) if a.count(str(sub*x))])
# 2