

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to remove duplicate characters from a given string in Python
Suppose we have a string s. We have to remove all duplicate characters that have already appeared before. The final string will have same ordering of characters like the actual one.
We can solve this by using ordered dictionary to maintain the insertion order of the characters. The value will be the frequency of those characters, however the frequency values are not important here. After forming the dictionary, we can simply take the keys and join them to get the string.
So, if the input is like s = "bbabcaaccdbaabababc", then the output will be "bacd".
- d := a dictionary where keys are stored in order by their insertion order
- for each character c in s, do
- if c is not present in d, then
- d[c] := 0
- d[c] := d[c] + 1
- if c is not present in d, then
- join the keys one after another in proper order to make the output string and return.
Example
Let us see the following implementation to get better understanding −
from collections import OrderedDict def solve(s): d = OrderedDict() for c in s: if c not in d: d[c] = 0 d[c] += 1 return ''.join(d.keys()) s = "bbabcaaccdbaabababc" print(solve(s))
Input
"bbabcaaccdbaabababc"
Output
"bacd"
- Related Questions & Answers
- C# Program to remove duplicate characters from String
- Java program to delete duplicate characters from a given String
- JavaScript Remove non-duplicate characters from string
- Python program to find all duplicate characters in a string
- Find All Duplicate Characters from a String using Python
- Python program to extract characters in given range from a string list
- How to remove specific characters from a string in Python?
- Java Program to find duplicate characters in a String?
- PHP program to remove non-alphanumeric characters from string
- How to Remove Characters from a String in Arduino?
- Java program to find all duplicate characters in a string
- Java Program to Find the Duplicate Characters in a String
- How to remove characters except digits from string in Python?
- Remove all duplicates from a given string in Python
- Extract only characters from given string in Python
Advertisements