Home » Interview Preparation » Python program to remove duplicates from string(order intact)

Python program to remove duplicates from string(order intact)

Support this post with a reaction:

4,130 views

In this tutorial, we will learn writing the python program to remove the duplicate characters from the string while preserving their order of string characters.

Problem Statement

Take a string from user as an input and check for duplicate characters. If there is any duplicate of characters found, then remove it.

For example:

Case1: If the user inputs the string ‘programmingLanguage’

Then the output should be ‘progaminLue’, where there is no character that is repeating.

Case2: If the user inputs the string ‘LearningIsFun’

Then the output should be ‘LearnigIsFu’, where there is no character that is repeating.

[elementor-template id=”5253″]

Our logic to remove duplicates from string

  • Firstly, take two strings as inputs from the user.
  • then, we make all characters stored in a set, which removes the duplicates.
  • then, use string concatenation methods to join the characters in the set together
  • And finally, return the concatenated string as an output of our program.

Algorithm to remove duplicates from string

Step1:  Start

Step2:   Take string as input from the user.

Step3: print  “ ”.join(dict.fromkeys(str1))

Step4: Stop

[elementor-template id=”5256″]

Python code to remove duplicates from string

Output :

Explanation:

Here, the user gives input as ‘aaabbcccd’, so first, the character of the string gets converted into elements of the dictionary, and the newly created dictionary value will be

‘ { ‘a’: None, ‘b’: None, ‘c’: None, ‘d’: None } ’

After that on join operation, the keys of the dictionary get concatenated in order and return the output as ‘abcd’.