Python program to find all duplicate characters in a string

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn how to find all duplicate values in a string. We can do it in different ways in Python. Let's explore them one by one.

The aim of the program we are going to write is to find the duplicate characters present in a string. For example, we have a string tutorialspoint the program will give us t o i as output. In simple words, we have to find characters whose count is greater than one in the string. Let's see.

Scratch Programs

Writing programs without using any modules. We can use different methods of Python to achieve our goal. First, we will find the duplicate characters of a string using the count method. Let's see the procedure first.

  • Initialize a string.
  • Initialize an empty list
  • Loop over the string.
    • Check whether the char frequency is greater than one or not using the count method.
If greater than one check whether it's present in the list or not.
If not present append to the list
  • Print the characters

Example

## initializing string
string = "tutorialspoint"
## initializing a list to append all the duplicate characters
duplicates = []
for char in string:
   ## checking whether the character have a duplicate or not
   ## str.count(char) returns the frequency of a char in the str
   if string.count(char) > 1:
   ## appending to the list if it's already not present
   if char not in duplicates:
   duplicates.append(char)
print(*duplicates)

If you run the above program, you will get the following results.

Output

t o i

Now we will find the duplicate characters of string without any methods. We are going to use the dictionary data structure to get the desired output. Let's see the procedure first.

  • Initialize a string.
  • Initialize an empty dictionary
  • Loop over the string.
    • Check whether the char is already present in the dictionary or not
    • Initialize the count of the char to 1
Increase the count

Example

## initializing string
string = "tutorialspoint"
## initializing a dictionary
duplicates = {}
for char in string:
   ## checking whether the char is already present in dictionary or not
   if char in duplicates:
      ## increasing count if present
      duplicates[char] += 1
   else:
      ## initializing count to 1 if not present
      duplicates[char] = 1
for key, value in duplicates.items():
   if value > 1:
      print(key, end = " ")
print()

If you run the above program,

Output

t o i
raja
Published on 27-Aug-2019 16:07:28
Advertisements