Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Find the frequency of each character - Python Program

Example 1 :

from collections import Counter text = "banana" freq = Counter(text) print(freq)

Output

 
OUTPUT  :
Counter({'a': 3, 'n': 2, 'b': 1})

Example 2 :

def character_frequency(input_string): """ Calculates the frequency of each character in a given string. Args: input_string (str): The string for which to calculate character frequencies. Returns: dict: A dictionary where keys are characters and values are their frequencies. """ frequency_dict = {} for char in input_string: frequency_dict[char] = frequency_dict.get(char, 0) + 1 return frequency_dict # Example Usage: text = "hello world" char_counts = character_frequency(text) print(f"Character frequencies in '{text}':") for char, count in char_counts.items(): print(f"'{char}': {count}") # Another Example: sentence = "Python Programming" sentence_counts = character_frequency(sentence) print(f"\nCharacter frequencies in '{sentence}':") for char, count in sentence_counts.items(): print(f"'{char}': {count}")

Output

 
OUTPUT  :
Character frequencies in 'hello world':
'h': 1
'e': 1
'l': 3
'o': 2
' ': 1
'w': 1
'r': 1
'd': 1

Character frequencies in 'Python Programming':
'P': 2
'y': 1
't': 1
'h': 1
'o': 2
'n': 2
' ': 1
'r': 2
'g': 2
'a': 1
'm': 2
'i': 1