1

I trying to find how many specific keyword in string but the output is not similar with the logic

input = raw_input('Enter the statement:') //I love u
keyword = raw_input('Enter the search keyword:') //love

count = 0

for i in input:
    if keyword in i:
        count = count + 1

print count
print len(input.split())

Expectation

1
3

Reality

0
3
halfer
  • 19,824
  • 17
  • 99
  • 186
Nurdin
  • 23,382
  • 43
  • 130
  • 308
  • 4
    Hint: if you put `print i` inside your loop, what do you think the output would be? Try it and see if it matches your prediction. – Kevin Mar 21 '16 at 17:36
  • i got like this one, i l o v e u – Nurdin Mar 21 '16 at 17:37
  • 1
    Exactly. You are iterating through the string: each character, not each word. Remember how you found the *number* of words? Do something similar to iterate through each word. – zondo Mar 21 '16 at 17:39

3 Answers3

3

input is a string, so iterating over it will give you each character individually. You probably meant to split it:

for i in input.split():

Note that using a list comprehension may be more elegant than a for loop:

count = len([x for x in input.split() if x in keyword])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Note that the `keyword in i` and the `x == keyword` methodologies are not the same. Consider the input "firetrucks put out fire" and the keyword "fire", the former returns 2 counts and the latter returns 1. – Jared Goguen Mar 21 '16 at 17:44
1

Let's look at the line for i in input. Here, input is a string which is an iterable in Python. This means you can do something like:

for char in 'string':
    print(char)
# 's', 't', 'r', 'i', 'n', 'g'

Instead, you can use the str.count method.

input.count(keyword)

As noted in a comment above, if you have the input "I want an apple" with the keyword "an", str.count will find two occurrences. If you only want one occurrence, you will need to split the input and then compare each word for equality.

sum(1 for word in input.split() if word == keyword)
Community
  • 1
  • 1
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
1

You need to turn the statement into a list, like this:

input = raw_input('Enter the statement:').split()   //I love u
keyword = raw_input('Enter the search keyword:')     //love

count = 0

for i in input:
    if keyword in i:
        count = count + 1

print count
print len(input)

This will allow the loop to correctly identify your desired items.

Tim S.
  • 2,187
  • 1
  • 25
  • 40