Find All Duplicate Characters from a String using Python

One String is given. Our task is to find those characters whose frequency is more than one in the given string.

As an example, we can see that the string “Hello World. Let’s learn Python” so the algorithm will find those letters which are occurring multiple times. In this case, the output will look like this -

e : 3
l : 4
o , 3)
<space> : 4 
r : 2
t : 2
n : 2

To implement this problem we are using Python Collections. From the collection, we can get the Counter() method. The Counter() method is used to count the hashtable objects. In this case, it separates the characters from the text and makes each character as a key of the dictionary, and the character count is the value of those keys.


Step 1: Find the key-value pair from the string, where each character is key and character counts are the values.
Step 2: For each key, check whether the value is greater than one or not. 
Step 3: If it is greater than one then, it is duplicate, so mark it. Otherwise, ignore the character 

Example Code

from collections import Counter
   freq_count = Counter(string) # get dictionary with letters as key and frequency as value
   for key in freq_count.keys():
      if freq_count.get(key) > 1: # for all different keys, list the letters and frequencies
         print("(" + key + ", " + str(freq_count.get(key)) + ")")
      myStr = 'Hello World. Let’s learn Python'    


(e, 3)
(l, 4)
(o, 3)
( , 4)
(r, 2)
(t, 2)
(n, 2)
Samual Sam
Samual Sam

Learning faster. Every day.