0

This post started as a question but in the meantime I've figured a solution for my problem. So now I would like to know how good ist it and if there is any better / more pythonic way to do it.

I am a newbie here and with python as well, any suggestions would be greatly appreciated!

The problem:

My aim was to count how many times a defined under-string: orange is to be found in a string:

string = "orangebananaorangeorangebanana"
counter = 0
for i in range(len(string)):
    if s[i:i+7] == "orange"
        counter = counter + 1
print(f"Orange is found {counter} times.")
Anna Jsk
  • 25
  • 5
  • 1
    See [How much research?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). You shouldn't post the question here until you've done a thorough search for how to count a substring. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Feb 05 '21 at 20:20

1 Answers1

0

Yes, there is a python function count to do so.

"orangebananaorangeorangebanana".count("orange")

Using an existing build-in function is more pythonic way to do things

Arseniy
  • 680
  • 5
  • 10