Python Count the Frequency of Each Character in a String
In Python, we can use a dictionary to count the occurrences of each character in a string. By iterating over each character in the string and using it as the dictionary key, the corresponding value is the number of times that character appears.
Example
def count_characters(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
# Example string
s = "hello world"
result = count_characters(s)
print(result)
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
# Example string
s = "hello world"
result = count_characters(s)
print(result)
Code explanation:
count_charactersThe function accepts a stringsas a parameter.char_countis an empty dictionary used to store characters and their occurrence counts.for char in s:Iterate over each character in the string.if char in char_count:Check whether the character is already in the dictionary. If it exists, increment that character's count by 1; if it does not exist, add the character to the dictionary and initialize the count to 1.- Finally, the function returns a dictionary containing the characters and their occurrence counts.
Output result:
Example
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Python3 Example