Skip to content
Programs · Program 4-5

Q.Write a program to count the number of times a character appears in a given string.

CBSENCERTSubjective· 3mImportance★★★★★est
23% · 7/30 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Concept understanding — Character Counting

A teacher marking attendance does not glance at the room and guess — she goes down the register one name at a time, keeping a running tally. Character counting in a program works the same way: a string is a sequence of characters, and to count something inside it you visit each character in turn and keep a tally of the ones that qualify. The skill being taught is not really "counting"; it is controlled traversal with a running total, one of the most reusable patterns in all of programming.

Python gives three levels of tool, and choosing the right one is part of the concept:

  • len() answers the crudest question — how many characters in total? It counts everything: letters, digits, spaces, punctuation. len("New Delhi") is 9, because the space is a character too.
  • The count() method answers a specific question — how many times does this exact piece of text occur? "banana".count("a") is 3. It counts non-overlapping occurrences and is case-sensitive.
  • A loop with a condition answers any question — how many vowels? how many digits? how many uppercase letters? You write the rule yourself:
text = input("Enter a sentence: ")
vowels = 0
for ch in text:
    if ch.lower() in "aeiou":
        vowels = vowels + 1
print("Vowel count:", vowels)
``` …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.