0

I'm trying to count letters inside a string using the .count function, the strings are stored inside a list and the count function is a different function inside a class.

For some reason the .count function will always give 0 in my code, and I can't seem to figure out why.

Class:

class string():

    def __init__(self, sentence):
        self.__s = sentence

    def setSentence(self, sentence):
        self.__s = sentence

    def getSentence(self):
        return self.__s

    def count(self):
        return self.__s.count("A")

Main:

if __name__ == '__main__':
    sentences = ["AABBA", "AAAAB", "BABBB"]
    x = string(sentences)
    for index in x.getSentence():
        print(x.count())

I was wondering if there's a way to use the .count function without putting the sentence's in the parameters of count()

user2390182
  • 72,016
  • 6
  • 67
  • 89
ItsWard
  • 23
  • 4
  • 1
    you're counting it wrong, either you join your words array into single string or you iterate through each word and initialize it as the string object individually and call count on each one. – darkash Dec 17 '20 at 12:07
  • 1
    print(`x.getSentence()`) will shed some light. Also `print(index)` might help. – kabanus Dec 17 '20 at 12:09
  • as an aside, `string` is not the greatest name or your class. Also, stop writing getters and setters in Python. – juanpa.arrivillaga Dec 17 '20 at 12:19
  • @juanpa.arrivillaga I am curious about your comment about stop writing getters and setters in python. Can you elaborate on this advice? What would be the alternative? I am asking thius question, so I and everyone else can learn from your experience. – itprorh66 Dec 18 '20 at 16:00
  • Just simply don't write them. They serve no purpose. You simply need an attribute, `self.sentence`. You don't need `getSentence` and `setSentence` methods, jsut *use the attribute*, `my_object.sentence` and `my_object.sentence = whatever`. Getters and setters serve no purpose in Python. Through the use of descriptors, e.g. `property` you have encapsulation without boilerplate getters and setters. – juanpa.arrivillaga Dec 18 '20 at 16:02
  • @itprorh66 see this answer: https://stackoverflow.com/a/36943813/5014455 – juanpa.arrivillaga Dec 18 '20 at 16:05
  • Thanks for the clarification – itprorh66 Dec 18 '20 at 16:43

1 Answers1

0

Your class expects a single str, not a list thereof. You can modify your code:

sentences = ["AABBA", "AAAAB", "BABBB"]

for s in sentences:
    x = string(s)
    print(x.count())

3
4
1

Typically, this kind of lapse would raise an error, but list also has a count method.

user2390182
  • 72,016
  • 6
  • 67
  • 89