0

I'm trying to print how many time a substring occurs.

When I try to print this I get the error-

Counter is undefined.

    s = str("eewd")
    substring = "e"
    def count_substring(s,substring):
        len1 = len(s)
        len2 = len(substring)
        i =0
        counter = 0
        while(i < len1):
            if(s[i] == substring[0]):
                if(s[i:i+len2] == substring):
                    counter += 1
            i += 1
    
        return counter

if __name__ == "__main__":
       print(counter)

Also is if __name__ == "__main__": needed in python 3?

Drophead
  • 19
  • 1
  • 7
  • There is a builtin function for these already https://docs.python.org/3/library/stdtypes.html?highlight=count#str.count – Carlos Gonzalez Sep 24 '20 at 12:02
  • Note that it looks as if you never call ``count_substring``. Did you intend to ``print(count_substring(s,substring))``? – MisterMiyagi Sep 24 '20 at 12:03
  • @CarlosGonzalez thanks for that, I'm trying to practice functions and loops first but appreciate that. – Drophead Sep 24 '20 at 12:08
  • @MisterMiyagi That's very useful, thank you. Also that's exactly it, fixed the issue. Thanks very much! – Drophead Sep 24 '20 at 12:08

0 Answers0