Python Count Occurrences of Each Letter in a String

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. count_lettersThe function accepts a stringsas a parameter.
  2. letter_countis an empty dictionary used to store each character and its occurrence count.
  3. for char in s:Iterates over each character in the string.
  4. if char in letter_count:Checks whether the character is already in the dictionary. If it exists, increments its corresponding value by 1.
  5. else:If the character is not in the dictionary, adds it to the dictionary and initializes the value to 1.
  6. Finally, returnsletter_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}

Document 对象参考手册Python3 Examples

Other extensions