Table of Contents

Count Times a Character Appears in a String

Example Description
This code allows you to input a string and then counts the number of times each character appears in the given string.

Introduction:

This code helps you count the number of times each character appears in a given string. By using a Python dictionary, the code creates a key-value pair where the character is the key and the frequency of its appearance is the corresponding value. The output is displayed by printing each key-value pair.

Code:

#Count the number of times a character appears in a given string
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
 if ch in dic: #if next character is already in the dictionary 
  dic[ch] += 1
 else:
  dic[ch] = 1 #if ch appears for the first time
for key in dic:
 print(key,':',dic[key])

Logic:

  1. Prompt the user to enter a string.
  2. Create an empty dictionary called “dic”.
  3. Iterate through each character in the given string using a for loop.
  4. Check if the character already exists in the “dic” dictionary. If yes, increase its corresponding value by 1.
  5. If the character is not yet in the dictionary, add it as a new key with a value of 1.
  6. Iterate through each key in the dictionary.
  7. Print the key-value pair, separating them with a colon.

Output:

The output of the code will be a list of key-value pairs, where each key represents a character from the input string, and the corresponding value represents the frequency of its appearance in the string.

Enter a string: Hello World

>> H : 1

>> e : 1

>> l : 3

>> o : 2

>> : 1

>> W : 1

>> r : 1

>> d : 1