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

Python Count the Occurrences of a Single Letter in a String

Python Count the Occurrences of a Single Letter in a String

Document Object Reference Manual Python3 Examples

In Python, we can use a dictionary to count how many times each letter appears in a string. By iterating over every character in the string and using it as a dictionary key, we can easily count the occurrences of each character.

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

text

=

"hello world"

result

=

count_characters

(

text

)

print

(

result

)

Code analysis:

  1. count_characters(s) is a function that takes a string s as its argument.
  2. char_count = {} Initialize an empty dictionary to store characters and their occurrence counts.
  3. for char in s: Iterate over each character in the string.
  4. if char in char_count: Check whether the current character is already in the dictionary.
  5. If it is already in the dictionary,char_count[char] += 1 increment the character's count by 1.
  6. If it is not in the dictionary,char_count[char] = 1 add the character to the dictionary and initialize its count to 1.
  7. - If it is already in the dictionary, `char_count[char] += 1` increments the character's count by 1. - If it is not in the dictionary, `char_count[char] = 1` adds the character to the dictionary and initializes its count to 1.
    1. return char_count Return the dictionary containing characters and their occurrence counts.
    2. text = "hello world" Define an example string.
    3. result = count_characters(text) Call the function and pass in the example string.
    4. print(result) Print the result.

    Output result:

    Example

    {

    'h'

    :

    1

    ,

    'e'

    :

    1

    ,

    'l'

    :

    3

    ,

    'o'

    :

    2

    ,

    ' '

    :

    1

    ,

    'w'

    :

    1

    ,

    'r'

    :

    1

    ,

    'd'

    :

    1

    }

    This output shows the number of occurrences of each character in the string "hello world". For example, the character 'l' appears 3 times, 'o' appears 2 times, and so on.

    Document Object Reference Manual Python3 Examples