Print highest frequency Character in String in Python

In this post, we will learn to write Python programs to print the highest frequency character in a String. We will see different approaches to achieve our requirements along with their explanations.

Problem statement:

For the Given input string we need to find the character(s) with the highest frequency. It means we have to print the character that has repeated the highest time. If there are multiple characters with the same highest frequency, we will print all of them.

For Example:

Input: “Hello, World!” Output: “l”

In the given input string Hello, World, the character “l” appears the most number of times, so printed print “l” as the output.

Method 1: Using a Dictionary

We will start with the approach that we discussed in the logic section.

string = input("Please Enter a string: ")
freq_dict = {}
# Count the frequency of each character
for char in string:
    if char in freq_dict:
        freq_dict[char] += 1
    else:
        freq_dict[char] = 1
max_freq = max(freq_dict.values())
# Print the characters with maximum frequency
for char in freq_dict:
    if freq_dict[char] == max_freq:
        print(char, end=' ')

Output 1:

Please Enter a string: quescol websites
e s 

Output 2:

Please Enter a string: hello world
l