Remove Characters and Duplicate in String Use of Set Datatype

In this class, we do a program to remove characters and duplicate in string use of set datatype.

For Complete YouTube Video: Click Here

Remove Character from a String

Q1) Write a program to remove a character from the given string.

All these programs will help you in improving your coding skills. You can easily crack the placement exams.

Logic

Logic is very simple. We use the inbuilt method provided on strings.

The replace method is used. To know more about string methods. Click here.

replace(ā€œnā€,ā€”) here replace method is searching for character n in the given string.

Where ever it finds the character, it is replaced with an empty string. Because we have given empty string in replace method.

In our program, we need an empty string because we have to remove the character n.

Program

string=input("enter your string")
character=input("enter the character to remove")[0]
string=string.replace(character,"")
print(len(string))
print(string)

Remove Duplicates in a String

Q2) Write a program to remove duplicates in a string.

Example:

x= Learning monkey.

In this, we have to remove duplicates. ie character n is present three times.

We need to place it one time.

Output:

learnig mokey

Logic

We use a set data type to remove duplicates from the string.

How simple the logic. Convert our string to set data type using type conversion.

Set data types do not make duplicates. It will consider the characters in the string only one time.

The problem with the set data type. It does not maintain order.

To maintain the order, we used a logic in the program given below.

Program

string=input("enter your string")
removeduplicates=set(string)
print(removeduplicates)
removeduplicates ="".join(removeduplicates) 
print(removeduplicates) 
order="" 
for i in string: 
    if(i in order): 
        pass
    else: 
        order=order+i 
print(order)