Skip to content
Related Articles

Related Articles

Python – Find all duplicate characters in string

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 12 Aug, 2022
View Discussion
Improve Article
Save Article

Given a string, find all the duplicate characters which are similar to each other. Let us look at the example. 

Examples:

Input : hello
Output : l

Input : geeksforgeeeks
Output : e g k s

We have discussed a solution in the below post. Print all the duplicates in the input string We can solve this problem quickly using the python Counter() method. 

The approach is very simple. 

  1. Create a dictionary using the Counter method having strings as keys and their frequencies as values.
  2. Declare a temp variable.
  3. Print all the indexes from the keys which have values greater than 1. 

Python




from collections import Counter
 
 
def find_dup_char(input):
 
    # now create dictionary using counter method
    # which will have strings as key and their
    # frequencies as value
    WC = Counter(input)
 
    # Finding no. of  occurrence of a character
    # and get the index of it.
    for letter, count in WC.items():
        if (count > 1):
            print(letter)
 
 
# Driver program
if __name__ == "__main__":
    input = 'geeksforgeeks'
    find_dup_char(input)

Output

e
g
k
s

Approach : Using count() method

Python3




def find_dup_char(input):
    x=[]
    for i in input:
        if i not in x and input.count(i)>1:
            x.append(i)
    print(" ".join(x))
 
# Driver program
if __name__ == "__main__":
    input = 'geeksforgeeks'
    find_dup_char(input)

Output

g e k s


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!