Python Count the Occurrences of Each Letter in a String
In Python, we can use a dictionary to count the occurrences of each letter in a string. By iterating over each character in the string and using it as a key in the dictionary, the corresponding value is the number of times that character appears.
Example
def
count_letters
(
s
)
:
letter_count
=
{
}
for
char
in
s:
if
char
in
letter_count:
letter_count
[
char
]
=
1
else
:
letter_count
[
char
]
=
1
return
letter_count
Example string
text
=
"hello world"
result
=
count_letters
(
text
)
(
result
)
Code analysis:
count_lettersThe function takes a stringsas its argument.letter_countis an empty dictionary used to store each character and its occurrence count.for char in s:Iterate over each character in the string.if char in letter_count:Check whether the character already exists in the dictionary. If it does, increment its corresponding value by 1.else:If the character is not in the dictionary, add it to the dictionary and initialize its value to 1.- Finally, return
letter_countdictionary, which contains each character and its occurrence count.
Output result:
Example
{
'h'
:
1
,
'e'
:
1
,
'l'
:
3
,
'o'
:
2
,
' '
:
1
,
'w'
:
1
,
'r'
:
1
,
'd'
:
1
}
Python3 Examples