Program to remove duplicate characters from the given string using Python

Introduction

In this section of python programming, our task is to remove the duplicate characters from the given string and return the output.

Program to remove duplicate characters from the given string

Program

from collections import OrderedDict


def rem_dup_unorder(x):
# Unordered output
    output = ''.join(set(x))
    print("String after removing duplicates using set() ", output)
    
def rem_dup_ord(x):
# Ordered output
    output = ''.join(OrderedDict.fromkeys(x))
    print("String after removing duplicates using OrderedDict.fromkeys()", output)
   
input_str = input("Enter the first string : ")
rem_dup_unorder(input_str)
rem_dup_ord(input_str)

Output

Program to remove duplicate characters from the given string Output

Explanation

From the output we can see that, we got two results; 1. The output in unordered form and 2. The output is in ordered form.

The set() is an unordered collection of unique elements. And by using join(), we have joined the two iterable elements and return the single string.

To get the output string in order, we have used OrderedDict(). The function OrderedDict() remembers the order of input string and fromkeys() create a new dictionary with key and value and returns the list of keys.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.