Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Count the Occurrences of Each Letter in a String

Python Count the Occurrences of Each Letter in a String

Document Object Reference Manual Python3 Examples

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

)

print

(

result

)

Code analysis:

  1. count_letters The function takes a string s as its argument.
  2. letter_count is an empty dictionary used to store each character and its occurrence count.
  3. for char in s: Iterate over each character in the string.
  4. if char in letter_count: Check whether the character already exists in the dictionary. If it does, increment its corresponding value by 1.
  5. else: If the character is not in the dictionary, add it to the dictionary and initialize its value to 1.
  6. Finally, return letter_count dictionary, 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

}

Document Object Reference Manual Python3 Examples