Reputation: 19
I'm trying to write a program to see how many times a 3-digit substring shows up in a string. For example, the substring "122" would show up in the string "122122" 2 times. However, whenever I run it, it returns 0, even if the substring does actually show up. Can you tell me what's wrong with my function?
def count_substring(string, sub_string):
count = 0
for i in range (len(string)):
if string[i:i+3] == sub_string:
count+=1
Upvotes: 0
Views: 45
Reputation: 141
Using @Samwise's comment as a suggestion:
def count_substring(string, sub_string):
return string.count(sub_string)
Although, since that's a one-liner, if you only need to run this function once, you may not even want to break it off into its own function. So just use string.count(sub_string)
where you need it.
Upvotes: 1
Reputation: 995
This can help you:
def count_substring(string, sub_string):
return string.count(sub_string)
Upvotes: 0