Programs · Program 4-5
Q.Write a program to count the number of times a character appears in a given string.
Puducherry CbseNCERTSubjective· 3mImportance★★★★★est
23% · 7/30 Questions
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 →Count how many times EVERY character appears in a string, using a dictionary keyed by character.
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if the character is already in dic
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key, ':', dic[key])
Output:
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.