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

Python Count the Frequency of Each Character in a String

Python Count the Frequency of Each Character in a String

Document Object Reference Manual Python3 Examples

In Python, we can use a dictionary to count how many times each character occurs in a string. Iterate over each character, use it as a dictionary key, and the corresponding value is the number of occurrences.

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

s

=

"hello world"

result

=

count_characters

(

s

)

print

(

result

)

Code analysis:

  1. count_characters The function takes a string s as its argument.
  2. char_count is an empty dictionary used 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 character is already in the dictionary. If it exists, increment its count by 1; if not, add the character to the dictionary with a count of 1.
  5. Finally, the function returns a dictionary containing the characters and their occurrence counts.

Output result:

Example

{

'h'

:

1

,

'e'

:

1

,

'l'

:

3

,

'o'

:

2

,

' '

:

1

,

'w'

:

1

,

'r'

:

1

,

'd'

:

1

}

Document Object Reference Manual Python3 Examples