1

I am trying to do the function count without using count() it is working and everything okay but when I try to search two letters in one word its returning 0. When I try to search 1 word in a letter its working normal.

def count(str, sub):
    found = 0
    for key in str:
        if key == sub:
            found += 1
    return found

str = input("Enter a string: ") #or we can initialize a string
sub = input("Enter a substring: ") #or we can initialize a substring

count(str, sub)

print ("letter: ", sub)
print ("count: ", count(str, sub))
6
  • for key in str: will always go one letter at a time, so you can not use existing logic to search for two characters at a time. Commented Feb 21, 2021 at 11:21
  • your loop is searching for 1 letter at a time Commented Feb 21, 2021 at 11:22
  • 1
    @tbjorch i mean without doing print('bctestbc'.count('bc')) to return 2 Commented Feb 21, 2021 at 11:23
  • @lllrnr101 yes now I realised that the for for loop will go one letter, any idea to turn into a word not letter by letter? Commented Feb 21, 2021 at 11:24
  • @VanshSachdeva yes now I realized, i am trying to find another method without letter by letter Commented Feb 21, 2021 at 11:24

3 Answers 3

3

Following your method I suggest you do something like this:

def count(string, sub):
    found = 0
    size = len(sub)
    for i in range(len(string) + 1 - size):
        if string[i:i+size] == sub:
            found += 1
    return found

That way you can use it for any size of sub.

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

Comments

2
def count(string, sub):
    found = 0

    for c in range(len(string)):
        start = c 
        end = -(len(string)-len(sub)-c) if -(len(string)-len(sub)-c) != 0 else None
        if string[start:end] == sub:
            found += 1
    return found

string = input("Enter a string: ") #or we can initialize a string
sub = input("Enter a substring: ") #or we can initialize a substring

print ("letter: ", sub)
print ("count: ", count(string, sub))

Comments

1

Below should work for all length sub strings.

def count(str, sub):
    found = 0
    for i in range(1,len(str)+1): #iterate for all length substrings
        for j in range(len(str)-i+1): #iterate for different starting positions of substrings.
            key = str[j:j+i]
            if key == sub:
                found += 1
    return found

1 Comment

as you can see here that this method is not working for this letter tested on programiz and uploaded on imgur

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.