0

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.

2
  • Possible duplicate of: stackoverflow.com/questions/8272358/… Commented Nov 4, 2020 at 12:04
  • You can use the built-in functions (like text.count()) or two pointers approach (l - first symbol, r - last, move forward sliding window and check substring text[l:r+1] while r < len(text) ) Commented Nov 4, 2020 at 12:35

3 Answers 3

2

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

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.