
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to remove string characters which have occurred before in Python
Suppose we have a string s. We have to remove those characters which have already occurred before, and return the reduced string. To solve this, we shall use one 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 = "cabbbaadac", then the output will be "cabd".
To solve this, we will follow these steps −
- 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 = "cabbbaadac" print(solve(s))
Input
"cabbbaadac"
Output
cabd
- Related Articles
- Program to remove duplicate characters from a given string in Python
- Program to find elements from list which have occurred at least k times in Python
- Python Program to Remove the Characters of Odd Index Values in a String
- C# Program to remove duplicate characters from String
- How to remove specific characters from a string in Python?
- How to remove characters except digits from string in Python?
- PHP program to remove non-alphanumeric characters from string
- How to remove a list of characters in string in Python?
- Python Program to Remove all digits before given Number
- C++ Program to Remove all Characters in a String Except Alphabets
- Program to swap string characters pairwise in Python
- Python program to remove each y occurrence before x in List
- Python Program to find mirror characters in a string
- Python Program to Capitalize repeated characters in a string
- Python program to check if both halves of the string have same set of characters.

Advertisements