Python: Count the number of characters (character frequency) in a string
Python String: Exercise-2 with Solution
Write a Python program to count the number of characters (character frequency) in a string.
Sample Solution:
Python Code:
# Define a function named char_frequency that takes one argument, str1.
def char_frequency(str1):
# Initialize an empty dictionary named 'dict' to store character frequencies.
dict = {}
# Iterate through each character 'n' in the input string str1.
for n in str1:
# Retrieve the keys (unique characters) in the 'dict' dictionary.
keys = dict.keys()
# Check if the character 'n' is already a key in the dictionary.
if n in keys:
# If 'n' is already a key, increment its value (frequency) by 1.
dict[n] += 1
else:
# If 'n' is not a key, add it to the dictionary with a frequency of 1.
dict[n] = 1
# Return the dictionary containing the frequency of each character in the input string.
return dict
# Call the char_frequency function with the argument 'google.com' and print the result.
print(char_frequency('google.com'))
Sample Output:
{'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
Flowchart:
Python Code Editor:
Previous: Write a Python program to calculate the length of a string.
Next: Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/string/python-data-type-string-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics