Count most repeated characters in a string Python

In this tutorial, we will learn to find the max frequent character in the string. Strings in Python are a sequence of characters wrapped inside single, double, or triple quotes. The frequency of a character is the total number of times that character occurs in the given string. We have to find and print the character which occurs the most in the string in our program.

Look at the examples to understand the input and output format.

Input: "bcbsvbsvbwberb"

Output: b

Input: "Studytonight"

Output: t

Approach

To execute this task, we can follow multiple approaches, some are discussed below:

  1. By using keys in the dictionary and max() method
  2. By using Counter() and max() method

We will discuss all three approaches in detail separately.

Approach 1: Keys of dictionary and max() method

In this approach, we will iterate through the string and form keys of the characters which occur in the string. The keys will have the value of how many times that character has occurred in the string. Then, using the max() method, we can find the key with the maximum count value, which will be then used to print the result.

The max() method returns the item with the highest value.

Algorithm

Step 1- Define a string with characters

Step 2- Declare an empty dictionary

Step 3- Run a loop to iterate through the string

Step 4- Add the character in the dictionary and keep a count of the frequency

Step 5- To get the maximum count use max() and store the value returned by it in a variable

Step 6- Print the variable which has the lowest count as the result

Python Program 1

In this program, we have defined a string with certain values and printed the least frequent character in that string using a dictionary char_freq, storing the characters and their occurrences as the key and its value. We can get the Key using the get() method.

string= "mississippis"
print(string)

char_freq={}

for i in string:
    if i in char_freq:
        char_freq[i]=char_freq[i]+1
    else:
        char_freq[i] = 1
result= max(char_freq, key = char_freq.get)

print("Most frequent character: ",result)


mississippis
Most frequent character: s

Approach 2: Counter() and max()

The Counter() method can be used to get the frequency of every character in the string then we can use the max() method to get the maximum count value.

The counter is a sub-class that counts all the hashable objects.

Algorithm

Step 1- Import Counter

Step 2- Declare a string with characters

Step 3- Print string

Step 4- Call the Counter() and pass the string

Step 5- To get the maximum count use max() and store the value returned by it in a variable

Step 6- Print the variable as the result

Python Program 2

In this program, to use Counter(), we have to import it from the collections class in our program. Since Counter works for hashable objects they are accessed using a key. We can get the Key using the get() method.

from collections import Counter

string= "pppppppghhhijeuupffe"
print(string)

result= Counter(string)
result= max(result, key=result.get)

print("Most frequent character: ",result)


pppppppghhhijeuupffe
Most frequent character: p

Conclusion

In this tutorial, we have seen two approaches to get the most frequent character from the string. The first approach was to find the maximum count using keys of a dictionary and using the key to print the most frequent character. The second approach was to use the Counter() method to get the total count for all characters. Using the max() method, we can get the maximum count value.

Sometimes you may need to count repeated characters in string in Python. There are several ways to do this in Python. In this article, we will learn how to count repeated characters in string in Python. We will look at three ways to count repeated characters in python string – using dictionary, using list comprehensions and using collections.


How to Count Repeated Characters in String in Python

Here are the steps to count repeated characters in python string. Let us say you have a string called ‘hello world’.


1. Using dictionary

In this case, we initiate an empty dictionary. Then we loop through the characters of input string one by one. For each character we increment the count of key-value pair where key is the given character. If the given key doesn’t exist then we create a new key-value pair with key as the character and value as 1. So by the time you have looped through the entire string you have a dictionary of all the unique alphabets as keys and their counts as the values. Here is the code to do the same.

#!/usr/bin/env python

input = "hello world"

d = {}

for c in input:
    try:
        d[c] += 1
    except:
        d[c] = 1

for k in d.keys():
    print "%s: %d" % (k, d[k])


2. Using Lists & Sets

You may also use List comprehensions to loop through the string and create a set of tuples where the first item is the character and the second item is its count. Here is an example to create a list of characters in string. In both the following cases, set function will convert the string into a list of its unique characters, including whitespace.

>>> s='hello world'

>>> [(i,s.count(i)) for i in set(s)]
[(' ', 1), ('e', 1), ('d', 1), ('h', 1), ('l', 3), ('o', 2), ('r', 1), ('w', 1)]

We can also do the same thing to create a dictionary of key-value pairs where the keys are the unique characters and values are their counts in input string.

>>> s='hello world'

>>> {i:s.count(i) for i in set(s)}
{' ': 1, 'e': 1, 'd': 1, 'h': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1}


3. Using Collections

Collections are dict subclasses but when you search for a key and it is not found, collections will create it for you, with value as 0. There are several types of collections available, most popular being defaultdict(int) and defaultdict(list) where you don’t need to write code for setting default values.

import collections

input='hello world'

d = collections.defaultdict(int)
for c in input:
    d[c] += 1

for c in sorted(d, key=d.get, reverse=True):
  print '%s %6d' % (c, d[c])

In the above code, we create a collection ‘d’, all you need to do is simply loop through your input string and increment the dict values whose key is equal to the given character. Once you have looped through the entire string, you will have counts of all unique characters in string, including whitespaces.

In this article, we have learnt three different ways to count repeated characters in python string. You can use any of them as per your convenience. They all work well even with large strings. Generally, this code is a part of a larger function or module in a python application or website. So you can modify it as per your requirement.

How to count number of repeated characters in a string Python?

Using list using count() method. The frequency of a character or substring within a string can be counted using the count() function of the Python language. As a return value, it simply provides the count of occurrences.

How do I find the most repeated chars in a string?

The steps required to find most frequent character in string are as follows:.
Create an array of size 256 and initialize with 0. ... .
Scan the string and increment array[str[i]] with 1..
Finally, scan the string again and find and compare the maximum corresponding value present in the hash array for each character..

How do you find the most frequent elements in a string in Python?

To find the most frequent element in the string, the max() function takes in two attributes which are the set() method and the key . Next, we'll pass the variable using the set() method which separates all the string alphabets while the variable key counts the number of times a specified value appears in the string.