Write a Python program to count the number of characters (character frequency) in a string


This program is written in Python and calculates the frequency of each character in a string.

  • The string "str" has a value "tutorjoes".
  • In the program, an empty dictionary called "dict" is created to store the frequency of each character in the string.
  • Next, a for loop is used to iterate through each character in the string "str". For each iteration, the keys of the dictionary "dict" are extracted using the "keys()" method and stored in a variable called "keys".
  • An if-else statement is used to check if the current character is already in the keys of the dictionary. If it is, the frequency of that character is increased by 1 using the "+=" operator. If the character is not present in the keys, a new key-value pair is added to the dictionary with the character as the key and a frequency of 1.
  • Finally, the program prints the dictionary "dict" using the "print()" function, which displays the frequency of each character in the string "str".

Source Code

str ="tutorjoes"
dict = {}
for c in str:
	keys = dict.keys()
	if c in keys:
		dict[c] += 1
	else:
		dict[c] = 1
print(dict)

Output

{'t': 2, 'u': 1, 'o': 2, 'r': 1, 'j': 1, 'e': 1, 's': 1}


Example Programs