Python Count the Frequency of Each Character in a String
In Python, we can use a dictionary to count how many times each character occurs in a string. Iterate over each character, use it as a dictionary key, and the corresponding value is the number of occurrences.
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
)
(
result
)
Code analysis:
count_charactersThe function takes a stringsas its argument.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 its count by 1; if not, add the character to the dictionary with a count of 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 Examples