PythonMastery
Python programs · Strings · beginner

Find the most frequent character in a string in Python

Count every character with a dictionary and find the one that appears most often. Handles ties, and shows the shorter Counter.most_common() way.

Count how many times each character appears, then pick the highest count. Spaces are skipped, because they are usually not what you want to count.

The program

python
text = input("Enter some text: ")

counts = {}
for ch in text:
    if ch != " ":
        counts[ch] = counts.get(ch, 0) + 1

highest = max(counts.values())
winners = [ch for ch in counts if counts[ch] == highest]

print(f"Most frequent: {', '.join(winners)} ({highest} times)")

Typed in this example: hello world. Press Run to type your own.

output
Enter some text: hello world
Most frequent: l (3 times)

How it works

Ties

In "programming", three letters appear twice. The program reports all three:

python
text = "programming"

counts = {}
for ch in text:
    counts[ch] = counts.get(ch, 0) + 1

highest = max(counts.values())
winners = [ch for ch in counts if counts[ch] == highest]
print(winners, highest)
output
['r', 'g', 'm'] 2

Another way: Counter

Counter from the collections module does the counting for you. most_common(3) gives the three most common characters with their counts:

python
from collections import Counter

counts = Counter("mississippi")
print(counts.most_common(3))
output
[('i', 4), ('s', 4), ('p', 2)]

When counts are equal, most_common() lists the character that appeared first in the text first.

Related programs: Count character frequency.

Learn the idea: Working with Strings, Dictionaries, collections: The Stdlib's Hidden Power