0

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
  
3
  • 2
    No return in your function? Commented Mar 21, 2021 at 20:55
  • 3
    It doesn't return 0, it returns None. You gotta return count at the end! Commented Mar 21, 2021 at 20:55
  • 3
    You can also just use the built-in count function. Try "122122".count("122")! Commented Mar 21, 2021 at 20:55

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

This can help you:

def count_substring(string, sub_string):
    return string.count(sub_string)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.