Home > database >  Can't count how many times a word appears in a string
Can't count how many times a word appears in a string

Time:06-03

I'm trying to solve this problem: Write a program that prints the number of times the string 'bob' occurs in s. But I'm struggling with my loop, if the I find the word in the string it adds 1 for every character in the string, think I might have to add a nested loop but don't know which. That's my code:

numOfBobs = 0
for word in s:
    if 'bob' in s:
        numOfBobs  = 1
print(numOfBobs)

CodePudding user response:

s = "bobtestbobabcbob"
numOfBobs = s.count("bob")
print(numOfBobs)

You can use string.count("word") for that

CodePudding user response:

for word in s won't really cut it, because while word looks like you mean a "word", Python doesn't know this. It is giving you a character.

def countSubstrings(input, search):
    result = 0
    currentIndex = 0
    while currentIndex   len(search) < len(input):
        if input[currentIndex:len(input)] == search:
            result  = 1
    return result

This is a short draft of how it could look like. Since this is a homework question (assumption, sorry), I'm going to leave it up to you to figure out the off-by-one errors and improvements (hint: len(x) is constant in these loops, so maybe pre-compute them).

CodePudding user response:

Try this :

for word in s:
    if 'bob' == word:
        numOfBobs  = 1
print(numOfBobs)

This will work if your input is list

  • Related