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
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.
Enter some text: hello world Most frequent: l (3 times)
How it works
counts.get(ch, 0)gives the current count forch, or 0 ifchis not in the dictionary yet. Adding 1 and storing the result counts the character.max(counts.values())is the highest count.- More than one character can have the highest count, so
winnerscollects all of them. They stay in the order they first appear in the text.
Ties
In "programming", three letters appear twice. The program reports all three:
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)
['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:
from collections import Counter counts = Counter("mississippi") print(counts.most_common(3))
[('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.