Python Program to Calculate the Number of Words and the Number of Characters Present in a String














































Python Program to Calculate the Number of Words and the Number of Characters Present in a String



Description:


This Python article focuses on counting characters and words present in a given string. The code has one class named Wc which stores the string. It then contains two functions, one to calculate the number of characters and one to calculate the number of words.
While calculating the number of characters, all Unicode characters are included. 
The number of words is calculated while keeping in mind, the typing conventions given at 
http://www.digitaldesk.org/EXTERNAL/SBOLP/CONTENT/SUBJECTS/SKLCHECK/WORD19.HTM
Which means that if the string does not follow those conventions, for example, the string contains a part where there is no space after the full stop, or there are spaces before and after the colon, then the results may differ. 

Code:

class Wc: def __init__(self, st): self.st = st def characters(self): return len(self.st) def words(self): if ":" in self.st: return len(self.st.split()) + self.st.count(":") return len(self.st.split()) def main(): st = input("Enter a string: ") chars = Wc(st).characters() words = Wc(st).words() print("Characters:", chars) print("Words:", words) if __name__ == '__main__': main()
Input:


Output:


Comments