A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-maximum-frequency-character-in-string/ below:

Maximum Frequency Character in String - Python

Maximum Frequency Character in String - Python

Last Updated : 12 Jul, 2025

The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times).

Using collection.Counter

Counter class from the collections module is an easy way to count the occurrences of each character in a string. It returns a dictionary-like object where keys are the characters and values are their frequencies.

Python
from collections import Counter

s = "hello world"

# Count the frequency of characters
frequency = Counter(s)

# Get the character with the maximum frequency
max_char = max(frequency, key=frequency.get)

print(max_char)

Explanation

Using dict.get() with max()

This method involves creating a dictionary to store the frequency of each character and then using the max() function to find the character with the highest frequency. The dict.get() method helps in counting occurrences efficiently.

Python
s = "hello world"

# Create a dictionary to store character frequencies
freq = {}

# Count the frequency of each character
for char in s:
    freq[char] = freq.get(char, 0) + 1

# Get the character with the maximum frequency
max_char = max(freq, key=freq.get)

print(max_char)

Explanation

Using str.count()

str.count() method counts the occurrences of a specific character in the string. By iterating over each unique character and using this method, we can find the one with the maximum frequency.

Python
s = "hello world"

# Initialize variables for tracking max frequency and character
max_char = ''
max_count = 0

# Loop through each unique character
for char in set(s):
    count = s.count(char)
    if count > max_count:
        max_count = count
        max_char = char

print(max_char)

Explanation

Using sorted() with key

sorted() function can be used to sort the characters based on their frequency. By passing a custom sorting key like s.count(char), we can sort the characters in descending order of frequency and select the first one.

Python
s = "hello world"

# Sort the string and find the character with the maximum frequency
max_char = sorted(set(s), key=lambda char: s.count(char), reverse=True)[0]

print(max_char)

Explanation



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4