Python program to find Least Frequent Character in a String


When it is required to find the least frequent character in a string, ‘Counter’ is used to get the count of letters. The ‘min’ method is used to get the minimum of values in the string, i.e every letter’s count is stored along with the letter. The minimum is obtained.

Example

Below is a demonstration of the same

from collections import Counter

my_str = "highland how"

print ("The string is : ")
print(my_str)

my_result = Counter(my_str)
my_result = min(my_result, key = my_result.get)

print ("The minimum of all characters in the string is : ")
print(my_result)

Output

The string is :
highland how
The minimum of all characters in the string is :
a

Explanation

  • The required packages are imported.

  • A string is defined, and is displayed on the console.

  • The ‘Counter’ is used to get the count of every letter in the string.

  • This is assigned to a variable.

  • The ‘min’ method is used to get the minimum of values.

  • This is assigned to the variable again.

  • This is displayed as output on the console.

Updated on: 20-Sep-2021

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements