Python Count 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 through each character in the string and using it as the key of 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)
print(result)
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)
print(result)
Code explanation:
count_lettersThe function accepts a stringsas a parameter.letter_countis an empty dictionary used to store each character and its occurrence count.for char in s:Iterates over each character in the string.if char in letter_count:Checks whether the character is already in the dictionary. If it exists, increments its corresponding value by 1.else:If the character is not in the dictionary, adds it to the dictionary and initializes the value to 1.- Finally, returns
letter_counta dictionary containing 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