1

I tried to create a program which returns the number of times a certain string occurs in the main string.

main_string="ABCDCDC"

find_string="CDC"

print(main_string.count(find_string))

Output=1

.... But there are 2 CDC. Is there any other ways to solve?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

1 Answers1

2

Try using regex:

print(len(re.findall(fr"(?={find_string})", main_string)))

Or try using this list comprehension:

x = len(find_string)
print(len([main_string[i:x + i] for i in range(len(main_string)) if main_string[i:x + i] == find_string]))

Both codes output:

2
U13-Forward
  • 69,221
  • 14
  • 89
  • 114