varsanov05
varsanov05

Reputation: 1

How many times a different word appear in a string - python

For example I have GolDeNSanDyWateRyBeaChSand and I need to find how many times the word sand appears.

text = input()
text = text.lower()
count = 0

if "sand" in text:
    count += 1

print(count)

But the problem is that there is 2 sand in this string and when it found the first one it stops. Im a beginner in the programming.

Upvotes: 0

Views: 740

Answers (3)

balderman
balderman

Reputation: 23815

Extending the solution offered by the OP.
The idea is to use find and move to towards the end of the string.
It is clear that count can be used here and the solution below is for educational purpose.

text = 'GolDeNSanDyWateRyBeaChSand'
word = 'sand'
ltext = text.lower()
offset = 0
counter = 0
while True:
    idx = ltext.find(word, offset)
    if idx == -1:
        break
    else:
        counter += 1
        offset = idx + len(word)
print(f'The word {word} was found {counter} times')

output

The word sand was found 2 times

Upvotes: 0

Alex Mandelias
Alex Mandelias

Reputation: 517

To find every occurrence of a string pattern inside another string s, even nested occurrences, do the following:

s = "sandsandssands"  # your string here
pattern = "sands"     # your pattern here

pos = -1
end_of_string = False

while not end_of_string:
    pos = s.find(pattern, pos+1)
    print(pos)
    end_of_string = (pos == -1)

Output

0
4
9
-1

Upvotes: 0

Daniel
Daniel

Reputation: 485

You can simply use the str.count() method to count how many times a string appears in another string.

text = input()
text = text.lower()
count = text.count("sand")

Upvotes: 2

Related Questions