HackerRank- Python Find a String



Print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.



  1. def count_substring(string, sub_string):
  2. count=0
  3. for i in range(0, len(string)-len(sub_string)+1):
  4. if string[i] == sub_string[0]:
  5. flag=1
  6. for j in range (0, len(sub_string)):
  7. if string[i+j] != sub_string[j]:
  8. flag=0
  9. break
  10. if flag==1:
  11. count += 1
  12. return count
  13. if __name__ == '__main__':
  14. string = input().strip()
  15. sub_string = input().strip()
  16. count = count_substring(string, sub_string)
  17. print(count)

download android app