[Tutor] Need to discuss about a class that can be used to print number of vowels, consonants, uppercase and lowercase letters and spaces in a string
Manprit Singh
manpritsinghece at gmail.com
Wed Aug 18 00:13:53 EDT 2021
Dear sir,
I have written below given program using a class that will print number of
vowels, consonants, uppercase and lowercase letters and spaces in a
string, provided string contains only alphabets and space
class StringStats:
def __init__(self):
self.str_seq = None
self.uppercase = None
self.lowercase = None
self.vowel = None
self.consonants = None
self.spaces = None
def set_string(self, seq):
self.str_seq = seq
def count_uppercase(self):
self.uppercase = sum(ch.isupper() for ch in self.str_seq)
def count_lowercase(self):
self.lowercase = sum(ch.islower() for ch in self.str_seq)
def count_vowels(self):
self.vowel = sum(ch in "AEIOUaeoiu" for ch in self.str_seq)
def count_consonants(self):
self.consonants = sum(ch not in "AEIOUaeoiu " for ch in
self.str_seq)
def count_space(self):
self.spaces = self.str_seq.count(" ")
def compute_stats(self):
self.count_uppercase()
self.count_lowercase()
self.count_vowels()
self.count_consonants()
self.count_space()
def show_stats(self):
print("String is-", self.str_seq)
print("Count of vowels-", self.vowel)
print("Count of consonants-", self.consonants)
print("Count of uppercase letters-", self.uppercase)
print("Count of lowercase letters", self.lowercase)
print("Count of spaces", self.spaces)
s_seq = "Amar Singh"
st1 = StringStats()
st1.set_string(s_seq)
st1.compute_stats()
st1.show_stats()
Gives the answer as below :
String is- Amar Singh
Count of vowels- 3
Count of consonants- 6
Count of uppercase letters- 2
Count of lowercase letters 7
Count of spaces 1
Just need your comments on this class against following points :
1) The way i have initialized all instance variables inside __init__(), later
on assigning values to each instance variable in different methods .
2) I have made different methods to set each instance variable, can't all
these instance variables be set in a single method ?
3) Any further improvement in the class
Regards
Manprit Singh
More information about the Tutor
mailing list