write a python program to Count the number of times a character appears in
a given string using a dictionary
Answers
Answered by
7
Given a string, the task is to count the frequency of a single character in that string. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters.
Method #1 : Naive method
Iterate the entire string for that particular character and then increase the counter when we encounter the particular character.
# Python3 code to demonstrate
# occurrence frequency using
# naive method
# initializing string
test_str = "GeeksforGeeks"
# using naive method to get count
# counting e
count = 0
for i in test_str:
if i == 'e':
count = count + 1
# printing result
print ("Count of e in GeeksforGeeks is : "
+ str(coun
Method #1 : Naive method
Iterate the entire string for that particular character and then increase the counter when we encounter the particular character.
# Python3 code to demonstrate
# occurrence frequency using
# naive method
# initializing string
test_str = "GeeksforGeeks"
# using naive method to get count
# counting e
count = 0
for i in test_str:
if i == 'e':
count = count + 1
# printing result
print ("Count of e in GeeksforGeeks is : "
+ str(coun
Answered by
2
Answer:
str = input("Enter the string: ")
ch = input("Enter the character to count: ");
c = str.count(ch)
print(ch, "occurs", c, "times")
OUTPUT
Enter the string: KnowledgeBoat
Enter the character to count: e
e occurs 2 times
Similar questions